fork download
  1. import java.util.*;
  2. import java.io.*;
  3. class KingdomUnity
  4. {
  5. static ArrayList<ArrayList<Integer>> map = new ArrayList<ArrayList<Integer>>();
  6. static int parent[]=new int[3051];
  7. static int visited[]=new int[3051];
  8. static int disc[]=new int[3051];
  9. static int low[]=new int[3051];
  10. static int ap[]=new int[3051];
  11. static int time=0;
  12. public static void main(String[]args)throws IOException
  13. {
  14. int T = Integer.parseInt(input.readLine());
  15. StringBuilder op = new StringBuilder();
  16. for(int i=0;i<=3000;i++)
  17. map.add(new ArrayList<Integer>());
  18. String[] inLine;
  19. while(T-->0)
  20. {
  21. //Resetting everything!
  22. Arrays.fill(parent,-1);
  23. Arrays.fill(visited,-1);
  24. Arrays.fill(ap,-1);
  25. Arrays.fill(disc,0);
  26. Arrays.fill(low,0);
  27. inLine = input.readLine().split(" ");
  28. int N = Integer.parseInt(inLine[0]);
  29. int M = Integer.parseInt(inLine[1]);
  30. int K = Integer.parseInt(inLine[2]);
  31. for(int i=0;i<N;i++)
  32. map.get(i).clear();
  33. //Inputting Graph
  34. for(int i=0;i<M;i++)
  35. {
  36. inLine = input.readLine().split(" ");
  37. int u = Integer.parseInt(inLine[0]);
  38. int v = Integer.parseInt(inLine[1]);
  39. map.get(u).add(v);
  40. map.get(v).add(u);
  41. }
  42. time=0;int ans=0;//Reset variable ans and time
  43. dfs(0);
  44. for(int i=0;i<N;i++)
  45. if(ap[i]==1)ans++;
  46. ans*=K;
  47. op.append(ans).append("\n");
  48. }
  49. input.close();
  50. System.out.println(op);
  51. }
  52.  
  53. static void dfs (int u)
  54. {
  55. int children=0;
  56. visited[u]=1;
  57. disc[u]=low[u]=++time;
  58. int sz = map.get(u).size();
  59. for(int i=0;i<sz;i++)
  60. {
  61. int v = map.get(u).get(i);
  62. if(visited[v]==-1)
  63. {
  64. children++;
  65. parent[v]=u;
  66. dfs(v);
  67. // Check if the subtree rooted with v has a connection to one of the ancestors of u
  68. low[u] = Math.min(low[u], low[v]);
  69. // u is an articulation point in following cases
  70. // (1) u is root of DFS tree and has two or more chilren.
  71. if (parent[u] == -1 && children > 1)
  72. ap[u]=1;
  73. // (2) If u is not root and low value of one of its child is more
  74. // than discovery value of u.
  75. if (parent[u] != -1 && low[v] >= disc[u])
  76. ap[u] = 1;
  77. }
  78. else if (v != parent[u])
  79. low[u] = Math.min(low[u], disc[v]);
  80. }
  81. }
  82. }
Success #stdin #stdout 0.11s 320320KB
stdin
1
7 6 5
0 1
1 2
3 4
2 4
2 6
5 2
stdout
15