Gym - 100712H
Gym - 100712H
tarjan无向图缩点+树上直径
#include<iostream> #include<cstdio> #include<queue> #include<algorithm> #include<cmath> #include<ctime> #include<set> #include<map> #include<stack> #include<cstring> #define inf 2147483647 #define ls rt<<1 #define rs rt<<1|1 #define lson ls,nl,mid,l,r #define rson rs,mid+1,nr,l,r #define N 100010 #define For(i,a,b) for(int i=a;i<=b;i++) #define p(a) putchar(a) #define g() getchar() using namespace std; int T; int n,m,x,y,now,Max,temp; int dfn[N],low[N]; int cnt,col,c[N]; bool vis[N]; struct node{ int n; node *next; }*e[N]; stack<int>s; void in(int &x){ int y=1; char c=g();x=0; while(c<'0'||c>'9'){ if(c=='-')y=-1; c=g(); } while(c<='9'&&c>='0'){ x=(x<<1)+(x<<3)+c-'0';c=g(); } x*=y; } void o(int x){ if(x<0){ p('-'); x=-x; } if(x>9)o(x/10); p(x%10+'0'); } void push(int x,int y){ node *p; p=new node(); p->n=y; if(e[x]==NULL) e[x]=p; else{ p->next=e[x]->next; e[x]->next=p; } } void tarjan(int x,int fa){ dfn[x]=low[x]=++cnt; vis[x]=true; s.push(x); for(node *i=e[x];i;i=i->next){ if(i->n==fa) continue;//无向图关键 if(!dfn[i->n]){ tarjan(i->n,x); low[x]=min(low[x],low[i->n]); } else if(vis[i->n]) low[x]=min(low[x],dfn[i->n]); } if(low[x]==dfn[x]){ col++; do{ now=s.top(); c[now]=col; s.pop(); vis[now]=0; }while(x!=now); } } void dfs(int x,int depth){ vis[x]=true; if(depth>Max){ Max=depth; temp=x; } for(node *i=e[x];i;i=i->next){ if(!vis[i->n]){ if(c[i->n]!=c[x]) dfs(i->n,depth+1); else dfs(i->n,depth); } } } void clear(){ cnt=0; Max=0; col=0; temp=0; memset(dfn,0,sizeof(dfn)); } int main(){ in(T); while(T--){ clear(); in(n);in(m); For(i,1,m){ in(x);in(y); push(x,y); push(y,x); } For(i,1,n) vis[i]=false; tarjan(1,1); For(i,1,n) vis[i]=false; dfs(1,0); For(i,1,n) vis[i]=false; dfs(temp,0); o(col-1-Max);p('\n'); For(i,1,n) e[i]=0; } return 0; }