Click to open link
Test instructions: To a non-connected map, there may be heavy side, ask to add an edge, so that the bridge in the diagram is the smallest, the number of bridges output
Idea: Just read the question, there is a thought to write, is nothing more than the Unicom map of the two components of the contraction point, and then beg for a longest road, end-to-end connection, will certainly more bridge contains make these bridges is no longer bridge, very good question, but the wrong 20+ what Ghost, MD heavy edge so difficult to deal with, drunk Before the practice is to find out all the heavy edges, hope that the data weakness water past, tle good, then we are in the processing of the bridge, that is, when looking for a bridge, if it is a bridge, we will mark this side, and then find all the side of the line, in one is to find the diameter of the tree, two times BFS can Very simple look at the code
#include <queue> #include <vector> #include <stdio.h> #include <string.h> #include <stdlib.h > #include <iostream> #include <algorithm>using namespace std;typedef long long ll;const int inf= 0x3f3f3f3f;const int maxn=200010;struct edge{int to,num; Edge (int a,int b) {to=a;num=b;}}; Vector<edge>g[maxn];vector<int>gg[maxn];int L[maxn],e[maxn],vis[maxn],stack1[maxn];int n,m,k,kk,cnt; void Dfs (int x,int fa) {vis[x]=1; L[x]=k; E[x]=k++;stack1[kk++]=x; int flag=0; for (unsigned int i=0;i<g[x].size (); i++) {Edge e=g[x][i]; if (E.TO!=FA) {if (!vis[e.to]) {DFS (e.to,x); L[x]=min (l[x],l[e.to]); if (L[e.to]>e[x]) {g[x][i].num=1; }}else L[x]=min (l[x],e[e.to]); }else{if (flag) l[x]=min (l[x],e[e.to]); flag++; }} if (L[x]==e[x]) {while (stack1[kk]!=x&&kk>0) {l[stACK1[KK-1]]=L[X]; kk--; vis[stack1[kk]]=0; }}}void Tarjan () {Kk=0;k=1;dfs (); for (int i=1;i<=n;i++) {for (unsigned int j=0;j<g[i].size (); j + +) {edge e=g[i][j]; if (l[i]!=l[e.to]&&e.num==1) {cnt++; Gg[l[i]].push_back (l[e.to]); Gg[l[e.to]].push_back (L[i]); }}}}int dis[maxn],v[maxn];void bfs (int s) {memset (dis,0,sizeof (dis)); memset (v,0,sizeof (v)); v[s]=1;dis[s]=0; queue<int>que; Que.push (s); while (!que.empty ()) {int U=que.front (); Que.pop (); for (unsigned int i=0;i<gg[u].size (); i++) {int t=gg[u][i]; if (v[t]==0) {v[t]=1; dis[t]=dis[u]+1; Que.push (t); }}}}int slove (int s) {int max1=0,pos=s; BFS (s); for (int i=1;i<=n;i++) {if (DIS[I]>MAX1) {pos=i;max1=dis[i]; }} BFS (POS); int ans=0; for (int i=1;i<=n;i++) {if (Dis[i]>ans) ans=dis[i]; } return ans; int main () {int flag,a,b; while (scanf ("%d%d", &n,&m)!=-1) {if (n==0&&m==0) break; for (int i=0;i<maxn;i++) {g[i].clear (); Gg[i].clear (); vis[i]=0; } for (int i=1;i<=m;i++) {scanf ("%d%d", &a,&b); if (a==b) continue; G[a].push_back (Edge (b,0)); G[b].push_back (Edge (a,0)); } Cnt=0;tarjan (); int Ans1=slove (1); printf ("%d\n", cnt-ans1); } return 0;}
HDU 4612 Double unicom component + Tree diameter