标签:tom 测试 重复 open 应该 输出 space 地图 --
1 10 1 1 9 1 8 8 10 10 3 8 6 1 2 10 4 9 5 3 7
-1 1 10 10 9 8 3 1 1 8
此题应该用dfs或bfs
dfs代码如下
1 #include <cstdio> 2 #include <vector> 3 #include <cstring> 4 5 using namespace std; 6 7 vector<int> path[100002]; 8 int pre[100002]; 9 10 int N, S; 11 12 void dfs(int start) { 13 int cnt = path[start].size(); 14 for(int i = 0; i < cnt;i++) { 15 int p = path[start][i]; 16 if(pre[p] == 0) { 17 pre[p] = start; 18 dfs(p); 19 } 20 21 } 22 } 23 int main(int argc, char const *argv[]) 24 { 25 int M; 26 //freopen("input.txt","r",stdin); 27 scanf("%d",&M); 28 while(M--) { 29 memset(path, 0, sizeof(path)); 30 memset(pre, 0, sizeof(pre)); 31 scanf("%d %d",&N,&S); 32 for(int i = 0; i < N-1; i++) { 33 int x,y; 34 scanf("%d %d",&x,&y); 35 path[x].push_back(y); 36 path[y].push_back(x); 37 } 38 pre[S] = -1; 39 dfs(S); 40 printf("%d", pre[1]); 41 for(int i = 2; i <= N; i++) { 42 printf(" %d",pre[i]); 43 } 44 puts(""); 45 } 46 return 0; 47 }
bfs代码如下
1 #include <cstdio> 2 #include <vector> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 7 vector<int> path[100002]; 8 int pre[100002]; 9 queue <int> que; 10 int N, S; 11 12 int main(int argc, char const *argv[]) 13 { 14 int M; 15 //freopen("input.txt","r",stdin); 16 scanf("%d",&M); 17 while(M--) { 18 memset(path, 0, sizeof(path)); 19 memset(pre, 0, sizeof(pre)); 20 scanf("%d %d",&N,&S); 21 for(int i = 0; i < N-1; i++) { 22 int x,y; 23 scanf("%d %d",&x,&y); 24 path[x].push_back(y); 25 path[y].push_back(x); 26 } 27 pre[S] = -1; 28 que.push(S); 29 30 while(!que.empty()) { 31 int p0 = que.front();que.pop(); 32 int cnt = path[p0].size(); 33 for(int i = 0; i < cnt;i++) { 34 int p = path[p0][i]; 35 if(pre[p] == 0) { 36 pre[p] = p0; 37 que.push(p); 38 } 39 } 40 } 41 printf("%d", pre[1]); 42 for(int i = 2; i <= N; i++) { 43 printf(" %d",pre[i]); 44 } 45 puts(""); 46 } 47 return 0; 48 }
标签:tom 测试 重复 open 应该 输出 space 地图 --
原文地址:http://www.cnblogs.com/jasonJie/p/6088409.html