Problem: Enter the edges of a node without a root tree and specify a root node that requires the tree to be converted to a root tree
Test Oj:nyoj http://acm.nyist.net/JudgeOnline/problem.php?pid=20
When the number of nodes is very large, if using the adjacency matrix to store the graph will occupy a lot of space, you can use the vector or adjacency table storage, because the vector memory growth mode problem may also cause memory too large problem, the adjacency table storage more advantageous
Code:
Using vector storage:
#include <iostream>#include<cstdio>#include<vector>#include<cstring>using namespacestd;Const intN =100005;intP[n];vector<int>G[n];voidBuildintUintFA) { intn =g[u].size (); for(intI=0; i<n; i++){ intv =G[u][i]; if(v = = FA)Continue; P[V]=u; Build (V, u); }}intMain () {intN, t, start; scanf ("%d", &t); while(t--) { for(intI=0; i<n; i++) g[i].clear (); scanf ("%d%d", &n, &start); intA, B; for(intI=0; i<n-1; i++) {scanf ("%d%d", &a, &b); G[a].push_back (b); G[b].push_back (a); } P[start]= -1; Build (Start,-1); if(N >=1) printf ("%d", p[1]); for(intI=2; i<=n; i++) printf ("%d", P[i]); printf ("\ n"); } return 0;}
Using adjacency List storage:
#include <iostream>#include<cstdio>#include<cstring>#include<stack>#include<map>using namespacestd;#defineN 100005intN;intP[n];intHead[n];intLen;structNode {intdata; intNext;} c[2*n];//twice times more space for nodes that do not specify a parent-child relationship (no map)voidInsertintAintb) {c[++len].data =b; C[len].next=Head[a]; Head[a]=Len;}voidBuildintUintFA) { for(intI=head[u]; I I=C[i].next) { intv =C[i].data; if(v = = FA)Continue; P[V]=u; Build (V, u); }}voidprint () {if(n>=1) printf ("%d", p[1]); for(intI=2; i<=n; i++) printf ("%d", P[i]); printf ("\ n");}voidinit () {len=0; memset (Head,0,sizeof(head)); Memset (c,0,sizeof(c)); Memset (P,0,sizeof(P));}intMain () {intT, start; scanf ("%d", &t); while(t--) {scanf ("%d%d", &n, &start); Init (); intA, B; for(intI=1; i<n; i++) {scanf ("%d%d", &a, &b); Insert (A, B); Insert (b, a); } P[start]= -1; Build (Start,-1); Print (); } return 0;}
No root tree to a root tree