标签:
题意:n个点,n-1条路,求出从点s出发到每一个点必须经过的前一个点,到自身为-1
思路:从s出发遍历一遍图就可以了,开flag数组记录下来每一个点的必经的点。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstdlib> 4 #include<cstring> 5 #include<string> 6 #include<queue> 7 #include<algorithm> 8 #include<map> 9 #include<iomanip> 10 #include<climits> 11 #include<string.h> 12 #include<cmath> 13 #include<stdlib.h> 14 #include<vector> 15 #include<stack> 16 #include<set> 17 using namespace std; 18 #define INF 1000000007 19 #define MAXN 4010 20 #define Mod 1000007 21 #define N 100010 22 #define NN 30 23 #define sigma_size 3 24 const int MAX = 1000100; 25 const int maxn = 6e5 + 10; 26 using namespace std; 27 typedef long long LL; 28 29 int T; 30 int n, s; 31 int u, v; 32 vector<int> G[100010]; 33 int flag[100010]; 34 35 void dfs(int u) 36 { 37 for (int i = 0; i < G[u].size(); ++i) { 38 int v = G[u][i]; 39 if (!flag[v]) { 40 flag[v] = u; 41 dfs(v); 42 } 43 } 44 } 45 46 void run() 47 { 48 cin >> n >> s; 49 for (int i = 0; i <= n; ++i) { 50 G[i].clear(); 51 flag[i] = 0; 52 } 53 for (int i = 1; i < n; ++i) { 54 scanf("%d%d",&u,&v); 55 G[u].push_back(v); 56 G[v].push_back(u); 57 } 58 flag[s] = -1; 59 dfs(s); 60 printf("%d", flag[1]); 61 for (int i = 2; i <= n; ++i) { 62 printf(" %d", flag[i]); 63 } 64 puts(""); 65 } 66 67 int main() 68 { 69 cin >> T; 70 while (T--) 71 run(); 72 //system("pause"); 73 return 0; 74 }
标签:
原文地址:http://www.cnblogs.com/usedrosee/p/4331289.html