The main idea: given n points, and M edge of the diagram of some of the edges may not be able to work at any time, so at least to add how many edges to be able to make the way any two side unicom?
Idea: It is obvious that as long as any two points in the graph are two sides to link. Then we can first build a new graph, and then count the number of points of the degree 1 ans, then the number of edges that need to be added is (ans+1)/2;
(PS; Because the diagram is a two-way map so, in the Tarjan shrinking point when you need to meet the edge will cross, and judge is not the same Unicom branch with num comparison! )
#include <map> #include <queue> #include <cmath> #include <cstdio> #include <stack># include<iostream> #include <cstring> #include <algorithm> #define LL int#define inf 0x3f3f3f3f#define EPS 1e-8#include<vector> #define LS l,mid,rt<<1#define rs mid+1,r,rt<<1|1using namespace Std;int n,m; const int Ma = 1000005;int head[ma],dfn[ma],num[ma],du[ma],stk[ma],vis[ma],low[ma];int cnt,top,time,css;bool mp[5100] [5100];struct node{int to,next;} Q[ma];void bu (int a,int b) {q[cnt].to = b; Q[cnt].next = Head[a]; Head[a] = cnt++;} void Init () {time = 1; CSS = top = CNT = 0; memset (dfn,0,sizeof (DFN)); memset (low,0,sizeof (Low)); memset (vis,0,sizeof (VIS)); memset (head,-1,sizeof (head)); memset (num,0,sizeof (num)); memset (du,0,sizeof (du)); Memset (Mp,false,sizeof (MP));} void Tarjan (int u,int to) {Low[u] = dfn[u] = time++; Vis[u] = 1; stk[top++] = u; for (int i = head[u]; ~i; i = q[i].next) {int v = q[i]. to; if (i = = (to^1)) continue; if (!vis[v]) {Tarjan (v,i); Low[u] = min (low[u],low[v]); } else Low[u] = min (low[u],dfn[v]); } if (low[u] = = Dfn[u]) {//Find great Unicom component css++; while (Top > 0&&stk[top]! = u) {top--; Vis[stk[top]] = 2; Num[stk[top]] = CSS; }}}int Main () {int k,i,j,a,b; while (~SCANF ("%d%d", &n,&m)) {init (); for (i = 0;i < m;++ i) {scanf ("%d%d", &a,&b);//////pay attention to the problem of heavy edges! if (Mp[a][b]) {continue; } Mp[a][b] = Mp[b][a] = true; Bu (a, b); Bu (b,a); } Tarjan (1,-1); for (i = 1;i <= n;++ i) for (j = head[i]; ~j; j = q[j].next) if (num[i]! = num[q[j].to]) Du[num[i]]++; int ans = 0; for (i = 1;i <= n;++ i) if (du[i] = = 1) ans++; printf"%d\n", (ans+1) >>1); } return 0;}
POJ 3352 Road construction&& POJ 3177 redundant Paths dual Unicom components