【题目链接:NYOJ-20

  很巧妙,要好好想想

#include <iostream>
#include <stdio.h>
#include <vector>
using namespace std;
vector<int>a[100005];
int b[100005],n,s;
void dfs(int x,int y){
    for (int i = 0; i <a[x].size();i++)
        if (a[x][i] != y)
            dfs(a[x][i],b[a[x][i]]=x);
        return;
}
int main(){
    int M,x,y;
    scanf("%d",&M);
    while (M--){
        scanf("%d%d",&n,&s);
        for (int i = 1; i <n; i++){
            a[i].clear();
        }
        for (int i = 1; i <n; i++){
            scanf("%d%d",&x,&y);
            a[x].push_back(y); //相当二维数组 
            a[y].push_back(x);
        }
        b[s] = -1;//与S相等则为-1  
        dfs(s,-1);
        for (int i = 1; i <= n; i++)
            printf("%d ",b[i]);
        printf("\n");
    }
    return 0;
}

 

相关文章:

  • 2021-10-25
  • 2022-12-23
  • 2022-12-23
  • 2021-09-20
  • 2021-12-30
  • 2021-12-21
  • 2022-01-04
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-02-11
  • 2021-12-10
  • 2021-06-02
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案