# HDU 4612 桥数-缩点后树的直径

1379人阅读 评论(2)

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<vector>
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<iostream>
#include<queue>
using namespace std;
#define inf 233333333
#define N 200010
#define M 2000010
struct Edge{
int from, to, nex;
bool cut;
}edge[M];
int bridgetop;
edge[ edgenum ] = E;
}
int n, m;
int dfn[N], low[N], tarjan_time, tar, Stack[N], top;
int Belong[N];
bool iscut[N];
void tarjan(int u, int fa){
dfn[u] = low[u] = ++tarjan_time;
Stack[++top] = u;
int child = 0, flag = 1;

for(int i = head[u]; ~i; i = edge[i].nex)
{
int v = edge[i].to;
if(flag && v==fa){flag = 0; continue;}
if(!dfn[v])
{
child++;
tarjan(v, u);
low[u] = min(low[u], low[v]);
if(low[v] >= dfn[u])
{
iscut[u] = true;

if(low[v]>dfn[u])
edge[i].cut = edge[i^1].cut = true;
}
}
else low[u] = min(low[u], dfn[v]);
}
if(child == 1 && fa<0)iscut[u] = false;
if(low[u] == dfn[u])
{
tar++;
do
{
Belong[ Stack[top] ] = tar;
}while(Stack[top--] != u);
}
}
vector<int>G[N];
int dis[N];
int BFS(int u){
for(int i = 0;i<=n;i++)dis[i] = inf;
dis[u] = 0;
queue<int>q;
q.push(u);
int pos = u, d = 0;
while(!q.empty()){
u = q.front(); q.pop();
for(int i=0;i<G[u].size();i++)
{
int v = G[u][i];
if(dis[v] > dis[u]+1)
{
dis[v] = dis[u]+1;
q.push(v);
if(dis[v] > d)d=dis[v] , pos = v;
}
}
}
return pos;
}
void init(){
memset(dfn, 0, sizeof(dfn));
memset(iscut, 0, sizeof(iscut));
memset(Belong, -1, sizeof(Belong));
bridgetop = 0;
tarjan_time = 0;
top = 0;
tar = 0;
}
int main(){
int i, j, u, v;
while(scanf("%d%d",&n,&m), m+n){
init();
while(m--){
scanf("%d %d",&u,&v);
}
for(i = 1; i <= n; i++)if(!dfn[i])
tarjan(i, -1);

for(i = 0; i <= tar; i++)G[i].clear();
int bri_cut = 0;
for(i = 0; i < edgenum; i+=2 )
{
u = Belong[edge[i].from], v = Belong[edge[i].to];
if(u != v)
G[u].push_back(v), G[v].push_back(u);
bri_cut += edge[i].cut;
}
u = BFS(1);
v = BFS(u);
printf("%d\n",bri_cut - dis[v]);
}
return 0;
}

0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：1077641次
• 积分：19437
• 等级：
• 排名：第494名
• 原创：865篇
• 转载：23篇
• 译文：0篇
• 评论：208条
文章分类
最新评论
大牛博客
wuyiqi
kuangbin
nero
rabbit
gx
tao
baka
jayye
lei

QQ对话
QQ