Description
Input
Output
Sample Input
2 16 1 14 8 5 10 16 5 9 4 6 8 4 4 10 1 13 6 15 10 11 6 7 10 2 16 3 8 1 16 12 16 7 5 2 3 3 4 3 1 1 5 3 5
Sample Output
4 3 思路:水的没法说了,不解释
#include<iostream> #include<cstdio> #include<cstring> #define FOR(i,a,b) for(int i=a;i<=b;++i) #define clr(f,z) memset(f,z,sizeof(f)) using namespace std; const int mm=10002; class Edge { public:int v,next; }e[mm+mm]; int qh[mm],head[mm],edge,rt[mm],id[mm]; bool vis[mm]; int anc[mm],n,m,root,ans; void data() { clr(qh,-1);clr(head,-1);edge=0; } void add(int u,int v,int*h) { e[edge].v=v;e[edge].next=h[u];h[u]=edge++; } int find(int x) { if(x^rt[x]) { rt[x]=find(rt[x]); } return rt[x]; } void dfs(int u) { int v; rt[u]=u;vis[u]=1; for(int i=head[u];~i;i=e[i].next) { v=e[i].v; if(!vis[v]) { dfs(v);rt[v]=u; } } for(int i=qh[u];~i;i=e[i].next) { v=e[i].v; if(vis[v]) { //printf("%d %d %d\n",u,v,find(v)); ans=find(v); } } } void find_bcc() { clr(vis,0); dfs(root); } int main() { int u,v,cas; while(~scanf("%d",&cas)) while(cas--) { data(); clr(id,0); scanf("%d",&n); FOR(i,2,n) { scanf("%d%d",&u,&v); id[v]++; add(u,v,head);add(v,u,head); } FOR(i,1,n) if(id[i]==0)root=i; scanf("%d%d",&u,&v); add(u,v,qh);add(v,u,qh); find_bcc(); printf("%d\n",ans); } }