矿场搭建

洛谷-P3225-矿场搭建open in new window

实现

#include <iostream>
#include <cstring>
#include <vector>
#include <stack>
using namespace std;

typedef long long LL;
const int N = 1010, M = 510;
struct edge {
    int to, next;
};
edge e[2 * M];
int idx, head[N];
int n, m, root;
int cnt, dfn[N], low[N];
bool cut[N];
stack<int> s;
int tot;
vector<int> dcc[N];

void add_edge (int u, int v) {
    e[idx].to = v;
    e[idx].next = head[u];
    head[u] = idx ++;
}
void tarjan (int cur) {
    low[cur] = dfn[cur] = ++ cnt;
    s.push(cur);
    if (cur == root && head[cur] == -1) {
        dcc[++ tot].push_back(cur);
        return;
    }
    int sum = 0;
    for (int i = head[cur]; i != -1; i = e[i].next) {
        int to = e[i].to;
        if (dfn[to] == 0) {
            tarjan(to);
            low[cur] = min(low[cur], low[to]);

            if (low[to] >= dfn[cur]) {
                ++ sum;
                if (cur != root || sum >= 2)
                    cut[cur] = true;
                ++ tot;
                int t;
                do {
                    t = s.top();
                    s.pop();
                    dcc[tot].push_back(t);
                } while (t != to);
                dcc[tot].push_back(cur);
            }
        } else {
            low[cur] = min(low[cur], dfn[to]);
        }
    }
}

int main () {
    int T = 0;
    while (scanf("%d", &m) && m) {
        for (int i = 1; i <= tot; ++ i) dcc[i].clear();
        n = idx = cnt = tot = 0;
        memset(head, -1, sizeof(head));
        memset(dfn, 0, sizeof(dfn));
        memset(cut, 0, sizeof(cut));

        for (int i = 1, u, v; i <= m; ++ i) {
            scanf("%d%d", &u, &v);
            n = max(n, max(u, v));
            add_edge(u, v);
            add_edge(v, u);
        }

        for (int i = 1; i <= n; ++ i) {
            if (dfn[i] == 0) {
                root = i;
                tarjan(i);
            }
        }
        LL res1 = 0, res2 = 1;
        for (int i = 1; i <= tot; ++ i) {
            int cnt = 0;
            for (int j = 0; j < dcc[i].size(); ++ j)
                if (cut[dcc[i][j]] == true)
                    ++ cnt;
            
            if (cnt == 0) {
                res1 += 2;
                res2 *= dcc[i].size() * (dcc[i].size() - 1) / 2;
            } else if (cnt == 1) {
                ++ res1;
                res2 *= dcc[i].size() - 1;
            }
        }
        printf("Case %d: %lld %lld\n", ++ T, res1, res2);
    }
    return 0;
}
最后修改于: