码迷,mamicode.com
首页 > 其他好文 > 详细

【DFS,双向】NYOJ-20-吝啬的国度

时间:2015-05-24 11:31:29      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

【题目链接: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;
}

 

【DFS,双向】NYOJ-20-吝啬的国度

标签:

原文地址:http://www.cnblogs.com/zhengbin/p/4525537.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!