标签:
Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)
Total Submission(s): 5093 Accepted Submission(s):
1131
//scc代表 双联通分量 写习惯了 顺手就写成scc了也懒得改了 #include<stdio.h> #include<string.h> #include<algorithm> #include<stack> #include<queue> #include<vector> #define MAXM 2000100 #define MAX 200100 #define INF 0x7fffff using namespace std; int n,m,bridge,sum; int low[MAX],dfn[MAX]; int head[MAX],ans,age; int sccno[MAX];//代表当前点属于哪个双连通分量 int dfsclock,scccnt; vector<int>newmap[MAX];//储存缩点后的新图 int instack[MAX];//标记当前点是否入栈 int dis[MAX];//求树的直径时记录路径的长度 int vis[MAX];//求树的直径时标记是否入队列 stack<int>s; struct node { int beg,end,next; }edge[MAXM]; void init() { ans=0; bridge=0; memset(head,-1,sizeof(head)); } void add(int u,int v) { edge[ans].beg=u; edge[ans].end=v; edge[ans].next=head[u]; head[u]=ans++; } void getmap() { int a,b; while(m--) { scanf("%d%d",&a,&b); add(a,b); add(b,a); } } void tarjan(int u,int fa) { int v,i; low[u]=dfn[u]=++dfsclock; instack[u]=1; s.push(u); int flag=1; for(i=head[u];i!=-1;i=edge[i].next) { v=edge[i].end; if(flag&&v==fa)//判重边 { flag=0; continue; } if(!dfn[v]) { tarjan(v,u); low[u]=min(low[u],low[v]); if(dfn[u]<low[v]) bridge++; } else if(instack[v]) low[u]=min(low[u],dfn[v]); } if(dfn[u]==low[u]) { scccnt++; while(1) { v=s.top(); s.pop(); instack[v]=0; sccno[v]=scccnt; if(v==u) break; } } } void find() { int i; memset(low,0,sizeof(low)); memset(sccno,0,sizeof(sccno)); memset(dfn,0,sizeof(dfn)); memset(instack,0,sizeof(instack)); dfsclock=scccnt=0; for(i=1;i<=n;i++) { if(!dfn[i]) tarjan(i,-1); } } void suodian() { int u,v,i,j; for(i=1;i<=scccnt;i++) newmap[i].clear(); for(i=0;i<ans;i=i+2) { u=sccno[edge[i].beg]; v=sccno[edge[i].end]; if(u!=v) { newmap[u].push_back(v); newmap[v].push_back(u); } } } void bfs(int beg) { queue<int>q; memset(dis,0,sizeof(dis)); memset(vis,0,sizeof(vis)); int i,j; while(!q.empty()) q.pop(); sum=0; age=beg; vis[beg]=1; q.push(beg); int u; while(!q.empty()) { u=q.front(); q.pop(); for(i=0;i<newmap[u].size();i++) { if(!vis[newmap[u][i]]) { dis[newmap[u][i]]=dis[u]+1; vis[newmap[u][i]]=1; q.push(newmap[u][i]); if(sum<dis[newmap[u][i]]) { sum=dis[newmap[u][i]]; age=newmap[u][i]; } } } } } void solve() { int i,j; bfs(1); bfs(age); printf("%d\n",bridge-sum); //printf("%d\n%d\n",bridge,sum); } int main() { while(scanf("%d%d",&n,&m),n|m) { init(); getmap(); find(); //printf("%d#\n",bridge); suodian(); solve(); } return 0; }
hdoj 4612 Warm up【双连通分量求桥&&缩点建新图求树的直径】
标签:
原文地址:http://www.cnblogs.com/tonghao/p/4874499.html