标签:
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
/*WA*/ import java.util.Scanner; public class 吝啬的国度{ static class Edge{ //邻接表 int v; int next; //int weight; 这里不需要 } static int[] first;// first[]头结点数组 static int tot; static int n; //节点数,边数 static Edge[] edge; //边 static int[] pre; public static void main(String[] args) { Scanner sc = new Scanner(System.in); int tcase = sc.nextInt(); while(tcase-->0){ n = sc.nextInt(); int S = sc.nextInt(); tot=0; edge = new Edge[2*n+1]; first = new int [2*n+1]; for(int i=1;i<=n;i++){ first[i] = -1; } pre = new int[n+1]; pre[S]=-1; for(int i=0;i<n-1;i++){ int u = sc.nextInt(); int v = sc.nextInt(); addEdge(u, v);//由于是双向的 addEdge(v, u); } DFS(S); for(int i=1;i<n;i++) System.out.print(pre[i]+" "); System.out.println(pre[n]); } } private static void DFS(int s) { for(int i=first[s];i!=-1;i=edge[i].next){ if(pre[edge[i].v]!=0) continue; pre[edge[i].v]=s; DFS(edge[i].v); } } private static void addEdge(int u, int v) { //构建邻接表 edge[tot] = new Edge(); edge[tot].v = v; edge[tot].next = first[u]; first[u] = tot++; } }
标签:
原文地址:http://www.cnblogs.com/liyinggang/p/5170906.html