-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphHa.java
125 lines (78 loc) · 1.96 KB
/
graphHa.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import java.io.*;
import java.util.*;
class graph{
private int n;
private LinkedList<Integer> adj[];
// int[] arr;
boolean visited[];
graph(int n){
this.n = n;
adj = new LinkedList[n];
for(int i = 0;i<n;i++){
adj[i] = new LinkedList();
}
// arr = new int[n];
visited = new boolean[n];
}
void addEdge(int a,int b){
adj[a].add(b);
adj[b].add(a);
}
int BFS(int s)
{
if(!visited[s]){
LinkedList<Integer> queue = new LinkedList<Integer>();
int k = 0;
visited[s]=true;
queue.add(s);
while (queue.size() != 0)
{
s = queue.poll();
Iterator<Integer> i = adj[s].listIterator();
while (i.hasNext())
{
int x = i.next();
if (!visited[x])
{
k++;
visited[x] = true;
// arr[x] =arr[s] + 1;
queue.add(x);
}
}
}
return k;
}else{
return -1;
}
}
}
public class tree {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
in.nextLine();
for(int i = 0;i<t;i++){
int n = in.nextInt();
int m = in.nextInt();
int cb = in.nextInt();
int r = in.nextInt();
graph g = new graph(n);
for(int j = 0;j<m;j++){
int a = in.nextInt();
int b = in.nextInt();
g.addEdge(a-1,b-1);
}
long sum = 0;
for(int k = 0;k<n;k++){
int p = g.BFS(k);
// System.out.println(p +" " + k);
if(p != -1){
sum += Math.min(p*r + cb, (p+1)*cb);
// c++;
}
}
System.out.println(sum);
}
}
}