原题:http://acm.hdu.edu.cn/showproblem.php?pid=3836
题意:问至少要加几条边,使得该图强连通(即图中任意两点都连通);
思路:先求原图的强连通分量,然后进行缩点构建新图,在新图中,求入度 = 0 和 出度 = 0 的个数,两者的最大值即为答案;
#include<cstdio> #include<cstring> #include<string> #include<algorithm> using namespace std; const int maxn = 200000+5; const int maxm = 500000+5; int n, m; int head[maxn], edgenum; int Stack[maxn], Belong[maxn], DFN[maxn], Low[maxn]; int Time, taj, top; bool Instack[maxn]; int in[maxn], out[maxn]; struct Edge { int from, to; int next; }edge[maxm]; void Tarjan(int u) { DFN[u] = Low[u] = ++Time; Stack[top++] = u; Instack[u] = true; for(int i = head[u];i != -1;i = edge[i].next) { int v = edge[i].to; if(DFN[v] == -1) { Tarjan(v); Low[u] = min(Low[u], Low[v]); } else { if(Instack[v] && Low[u] > DFN[v]) Low[u] = DFN[v]; } } if(DFN[u] == Low[u]) { taj++; while(1) { int now = Stack[--top]; Belong[now] = taj; Instack[now] = false; if(now == u) break; } } } void add(int u, int v) { edge[edgenum].from = u; edge[edgenum].to = v; edge[edgenum].next = head[u]; head[u] = edgenum++; } void init() { memset(head, -1, sizeof head); edgenum = 0; memset(DFN, -1, sizeof DFN); memset(Instack, false, sizeof Instack); Time = taj = top = 0; } int main() { while(~scanf("%d%d", &n, &m)) { init(); while(m--) { int u, v; scanf("%d%d", &u, &v); add(u, v); } for(int i = 1;i<=n;i++) { if(DFN[i] == -1) Tarjan(i); } if(taj == 1) { printf("0\n"); continue; } memset(in, 0, sizeof in); memset(out, 0, sizeof out); for(int i = 0;i<edgenum;i++) { int u = Belong[edge[i].from]; int v = Belong[edge[i].to]; if(u != v) { out[u]++; in[v]++; } } int incnt = 0, outcnt = 0; for(int i = 1;i<=taj;i++) { if(in[i] == 0) incnt++; if(out[i] == 0) outcnt++; } printf("%d\n", max(incnt, outcnt)); } return 0; }