-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUva11631.java
More file actions
106 lines (95 loc) · 2.82 KB
/
Copy pathUva11631.java
File metadata and controls
106 lines (95 loc) · 2.82 KB
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
import java.util.*;
import java.io.*;
public class Uva11631
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pr = new PrintWriter(System.out);
StringBuilder sb = new StringBuilder();
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
while (n!=0&&m!=0)
{
Edge [] edgeList = new Edge[m];
UF uf = new UF(n+1);
int minCost = 0 ;
int maxCost = 0 ;
for(int i = 0 ; i < m ; i++)
{
st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
int z = Integer.parseInt(st.nextToken());
edgeList[i] = new Edge(x,y,z);
maxCost += z ;
}
Arrays.sort(edgeList);
for(int i = 0 ; i < m ; i++)
{
Edge e = edgeList[i];
int u = e.u ;
int v = e.v;
int w = e.weight;
if(uf.connected(u,v)) continue;
uf.union(u,v);
minCost += w ;
}
sb.append(maxCost-minCost+"\n");
st = new StringTokenizer(br.readLine());
n = Integer.parseInt(st.nextToken());
m = Integer.parseInt(st.nextToken());
}
pr.print(sb.toString());
pr.close();
br.close();
}
static class Edge implements Comparable<Edge>
{
int u , v , weight ;
public Edge(int x , int y , int z)
{
u = x ; v = y ; weight = z ;
}
public int compareTo(Edge that)
{
if (this.weight > that.weight) return 1 ;
else if(this.weight < that.weight) return -1 ;
else return 0 ;
}
}
static class UF
{
private int [] id ;
private int count ;
public UF(int N)
{
count = N ;
id = new int[N];
for (int i = 0; i < N; i++)
id[i] = i ;
}
public int count()
{
return count ;
}
public boolean connected(int p , int q)
{
return find(p) == find(q);
}
public int find(int p)
{
return id[p];
}
public void union(int p ,int q)
{
int pID = find(p);
int qID = find(q);
if(qID==pID) return ;
for (int i = 0; i < id.length; i++)
if(id[i]==pID) id[i]=qID;
count-- ;
}
}
}