pat 1076

一点教训

由于思维惯式,总是喜欢用DFS解题,,,

当题目提示在限定的层数下进行解题的时候,一定要想到BFS http://www.patest.cn/contests/pat-a-practise/1076

此题不难,如果考试出来应该要对的,,,,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
//此题应该使用BFS
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#define MAX 1010
using namespace std;
int n , l;
int M[MAX] = {0};
vector<int> G[MAX];
bool vis[MAX] = {false};
int cnt = 0;//计数
void DFS(int root , int depth)
{
if(depth > l)
return;
vis[root] = true;
++cnt;
for(int i = 0 ; i < G[root].size() ; ++i)
{
int v = G[root][i];
if(vis[v] == false)
{
vis[v] = true;
DFS(v , depth +1);
}
}
}
void BFS(int root)
{
vis[root] = true;
int layer = 0;
int front = 0 , last = 1 , rear = 0;
queue<int> q;
q.push(root);
++rear;
while(!q.empty())
{
int now = q.front();
q.pop();
++front;
++cnt;
for(int i =0 ; i < G[now].size() ; ++i)
{
int v = G[now][i];
if(vis[v] == false)
{
vis[v] = true;
q.push(v);
++rear;
}
}
if(front == last)
{
++layer;
if(layer > l)
break;
last = rear;
}
}
}
int main()
{
cin>>n>>l;
int i , j;
int num , id;
for(i = 1 ; i <= n ; ++i)
{
cin>>num;
for(j = 0 ; j < num ; ++j)
{
cin>>id;
G[id].push_back(i);
}
}
int numCheck , currentPoint;
cin>>numCheck;
for(i = 0 ; i < numCheck ; ++i)
{
fill(vis , vis+MAX , false);
cin>>currentPoint;
//修改与当前节点相关的方向
/* for(int k = 1 ; k <= n ; ++k)
{
for(int x = 0 ; x < G[k].size() ; ++x)
{
if(G[k][x] == currentPoint)
{
G[currentPoint].push_back(k);
}
}
}*/
//DFS(currentPoint , 0);
BFS(currentPoint);
cout<<cnt-1<<endl;
cnt = 0;
}
return 0;
}

热评文章