Gym 100712H
Gym 100712H
https://vjudge.net/problem/195715/origin
先缩点,再建立新图,然后跑两遍dfs求树上最长路
#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 200010 #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,cnt,col,now,S,Max; int dfn[N],low[N],c[N],ans; bool vis[N]; struct node{ int n; node *next; }*e[N]; stack<int>s; struct edge{ int x;int y; }a[N]; 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]==0) 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]=1; s.push(x); for(node *i=e[x];i;i=i->next){ if(!dfn[i->n]){ tarjan(i->n,x); low[x]=min(low[x],low[i->n]); } else if(vis[i->n]&&i->n!=fa) low[x]=min(low[x],dfn[i->n]); } if(low[x]==dfn[x]){ col++; do{ ans++; now=s.top(); c[now]=col; s.pop(); vis[now]=0; }while(x!=now); } } void dfs(int x,int fa,int deep){ if(Max<deep){ Max=deep; S=x; } for(node *i=e[x];i;i=i->next) if(i->n!=fa) dfs(i->n,x,deep+1); } void clear(){ memset(vis,0,sizeof(vis)); memset(dfn,0,sizeof(dfn)); memset(c,0,sizeof(c)); memset(low,0,sizeof(low)); memset(e,0,sizeof(e)); Max=0; col=0; cnt=0; } int main(){ in(T); while(T--){ clear(); in(n);in(m); For(i,1,m){ in(x);in(y); a[i].x=x; a[i].y=y; push(x,y); push(y,x); } tarjan(1,0); memset(e,0,sizeof(e)); For(i,1,m) if(c[a[i].x]!=c[a[i].y]){ push(c[a[i].x],c[a[i].y]); push(c[a[i].y],c[a[i].x]); } dfs(1,1,0); Max=0; dfs(S,S,0); o(col-Max-1);p('\n'); } return 0; }