☆1021
没有用并查集,自己做的
#include <cstdio> #include <vector> #include <cstring> using namespace std; const int N=10010; vector<int>tree[N]; bool vis[N]; int result[N]; int component = 1; int len; int max_height=-1; int get_height(int v) { vis[v]=true; bool leaf=true; int height; int M=0; for(int i=0; i<tree[v].size(); i++) { if(vis[tree[v][i]]==false) { height=get_height(tree[v][i])+1; if(height>M)M=height; leaf=false; } } if(leaf)return 0; else return M; } int main() { scanf("%d",&len); for(int i=1; i<len; i++) { int a, b; scanf("%d %d",&a,&b); tree[a].push_back(b); tree[b].push_back(a); } for(int i=1; i<=len; i++) { memset(vis,false,sizeof(vis)); int h=get_height(i); if(i==1) { for(int j=1; j<=len; j++) { if(vis[j]==false) { component++; get_height(j); } } if(component>1) { printf("Error: %d components",component); return 0; } } if(h>max_height) { max_height=h; } result[i]=h; } for(int i=1; i<=len; i++) { if(result[i]==max_height)printf("%d\n",i); } return 0; }
- 没有考虑到N==1的情形,不过答案也是对的。因为maxheight被更新了,这样看来,设置成负数也挺好的。