1.建树时寻找树的根
vector<int>tree[N];
int root = -1;
/*错误代码,思路是如果当前root存的节点不是根,
那么一定会有对应的father节点,因此总会更新为它的father节点
直到root是真正根节点,才不会被更新。
*/
void build(){
int n;cin>>n;
for(int i = 0;i<n;i++){
int child,father;cin>>child>>father;
if(child==root||root==-1){
root = father;
}
tree[father].push_back(child);
}
}
/*最终结果不一定是root,因为给出的father->child顺序是乱的,
可能导致当前root并非根,然而由于当前节点的father在之前已经给出,
因此root不会再被更新。
*/
//正解
bool childs[n];
void build(){
int n;cin>>n;
for(int i = 0;i<n;i++){
int child,father;cin>>child>>father;
childs[child] = true;
tree[father].push_back(child);
}
for(int i = 0;i<n;i++){
if(!child[i]){
root = i;
break;
}
}
}