縮點+樹的直徑+擴棧
4 4 1 2 1 3 1 4 2 3 0 0
0
#include#include #include #include #include #include #include #pragma comment(linker, "/STACK:1024000000,1024000000") using namespace std; const int maxn=220000; struct Edge { int from,to,next,id; }edge[maxn*10],edge2[maxn*10]; int Adj[maxn],Size,n,m; int Adj2[maxn],Size2; void init() { Size=0; memset(Adj,-1,sizeof(Adj)); } void init2() { Size2=0; memset(Adj2,-1,sizeof(Adj2)); } void Add_Edge(int u,int v,int id) { edge[Size].from=u; edge[Size].id=id; edge[Size].to=v; edge[Size].next=Adj[u]; Adj[u]=Size++; } void Add_Edge2(int u,int v) { edge2[Size2].from=u; edge2[Size2].to=v; edge2[Size2].next=Adj2[u]; Adj2[u]=Size2++; } int Low[maxn],DFN[maxn],Stack[maxn],Belong[maxn]; int Index,top,scc; bool Instack[maxn],vis[maxn],ve[maxn*10]; void Tarjan(int u,int fa) { int v; Low[u]=DFN[u]=++Index; Stack[top++]=u; Instack[u]=true; for(int i=Adj[u];~i;i=edge[i].next) { v=edge[i].to; if(v==fa&&ve[edge[i].id]) continue; ve[edge[i].id]=true; if(!DFN[v]) { Tarjan(v,u); Low[u]=min(Low[u],Low[v]); } else { Low[u]=min(Low[u],DFN[v]); } } if(Low[u]==DFN[u]) { scc++; do { v=Stack[--top]; Belong[v]=scc; Instack[v]=false; }while(v!=u); } } void scc_solve() { memset(DFN,0,sizeof(DFN)); memset(Instack,0,sizeof(Instack)); Index=scc=top=0; memset(ve,0,sizeof(ve)); for(int i=1;i<=n;i++) { if(!DFN[i]) Tarjan(i,i); } } struct PT { int p,d; PT() {} PT(int a,int b):p(a),d(b) {} }; int main() { while(scanf("%d%d",&n,&m)!=EOF) { if(n==0&&m==0) break; init(); for(int i=0;i q; memset(vis,0,sizeof(vis)); q.push(stp); vis[stp.p]=true; while(!q.empty()) { PT u,v; u=q.front(); q.pop(); edp=u; for(int i=Adj2[u.p];~i;i=edge2[i].next) { v.p=edge2[i].to; v.d=u.d+1; if(vis[v.p]) continue; vis[v.p]=true; q.push(v); } } while(!q.empty()) q.pop(); stp.p=-1,stp.d=-1; memset(vis,0,sizeof(vis)); vis[edp.p]=true; edp.d=0; q.push(edp); while(!q.empty()) { PT u,v; u=q.front(); q.pop(); stp=u; for(int i=Adj2[u.p];~i;i=edge2[i].next) { v.p=edge2[i].to; v.d=u.d+1; if(vis[v.p]) continue; vis[v.p]=true; q.push(v); } } printf("%d\n",ans-stp.d); } return 0; }