Nyoj 20 吝啬的国度

题目来源:http://acm.nyist.net/JudgeOnline/problem.php?pid=20

有两种搜索方式,深搜或者广搜都可以;

#include <iostream>
#include <cstring>
#include <cstdio>
#include <vector>
using namespace std;
const int MAXN = 100010;

vector <int> Graph[MAXN];
int preNode[MAXN];

/**
void DFS(int CurNode)
{
    for(int i = 0; i < Graph[CurNode].size(); ++i)
    {
        if(preNode[ Graph[CurNode][i] ])//如果当前节点已经访问过,那么就继续搜索CurNode的下一个邻接点
            continue ;
        preNode[ Graph[CurNode][i] ] = CurNode;
        DFS(Graph[CurNode][i]);
    }
    return ;
}
*/

void BFS(int CurNode)
{
    int que[MAXN], qs, qe;
    memset(que, 0, sizeof(que));
    qe = qs = 0;
    que[qe++] = CurNode;
    while(qs < qe)
    {
        int u = que[qs++];
        for(int i = 0; i < Graph[u].size(); ++i)
        {
            if(preNode[ Graph[u][i] ])
                continue ;
            preNode[Graph[u][i]] = u;
            que[qe++] = Graph[u][i];
        }
    }
}
int main()
{
    int T;
    int n, start;
    int a, b;
    scanf("%d", &T);
    while(T--)
    {
        scanf("%d %d", &n, &start);
        memset(Graph, 0, sizeof(Graph));
        memset(preNode, 0, sizeof(preNode));

        for(int i = 0; i < n-1; ++i)
        {
            scanf("%d %d", &a, &b);
            Graph[a].push_back(b);//只要相邻就添加双向边
            Graph[b].push_back(a);
        }
        preNode[start] = -1;
        //DFS(start);
        BFS(start);
        for(int i = 1; i <= n; ++i)
            printf("%d ", preNode[i]);
    }
    return 0;
}


你可能感兴趣的:(搜索)