ny吝啬的国王

1. import java.util.ArrayDeque;
02. import java.util.Queue;
03. import java.util.Scanner;
04.  
05. public class Main {
06.  
07. public static final int N = 100001;
08. public static Vertex[] list = new Vertex[N];
09. public static int[] tag;
10.  
11. public static void main(String[] args) {
12. Scanner sc = new Scanner(System.in);
13. int caseCount = sc.nextInt();
14. while(caseCount-- > 0) {
15. int vertexCount = sc.nextInt();
16. tag = new int[vertexCount+1];
17. int startVertex = sc.nextInt();
18. init(vertexCount);
19. for(int i=1; i<vertexCount; i++) {
20. int v1 = sc.nextInt();
21. int v2 = sc.nextInt();
22. insertList(v1, v2);
23. }
24. search(startVertex);
25. show();
26. }
27. }
28.  
29. private static void show() {
30. for(int i=1; i<tag.length-1; i++) {
31. System.out.print(tag[i] + " ");
32. }
33. System.out.println(tag[tag.length-1]);
34. }
35.  
36. private static void search(int startVertex) {
37. Queue<Vertex> queue = new ArrayDeque<Vertex>();
38. queue.add(new Main().new Vertex(startVertex, null));
39. Vertex temp;
40. int parent;
41. tag[startVertex] = -1;
42. while(!queue.isEmpty()) {
43. parent = queue.poll().vertex;
44. temp = list[parent];
45. while(temp != null) {
46. if(tag[temp.vertex] == 0) {
47. tag[temp.vertex] = parent;
48. queue.add(temp);
49. }
50. temp = temp.link;
51. }
52. }
53. }
54.  
55. private static void insertList(int v1, int v2) {
56. list[v1] = new Main().new Vertex(v2, list[v1]);
57. list[v2] = new Main().new Vertex(v1, list[v2]);
58. }
59.  
60. private static void init(int vertexCount) {
61. for(int i=1; i<=vertexCount; i++) {
62. list[i] = null;
63. }
64. }
65.  
66. class Vertex {
67. int vertex;
68. Vertex link;
69.  
70. public Vertex(int vertex, Vertex link) {
71. this.vertex = vertex;
72. this.link = link;
73. }
74. }
75.  
76. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值