Online Judge | Problem Set | Authors | Online Contests | User | ||||||
---|---|---|---|---|---|---|---|---|---|---|
Web Board Home Page F.A.Qs Statistical Charts | Current Contest Past Contests Scheduled Contests Award Contest |
JAVA, Kruskal, union-findpackage com.company; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Arrays; import java.util.Comparator; import java.util.StringTokenizer; public class Main { static int[] par; static int[] rank; public static void main(String[] args) throws IOException { sc.init(System.in ); int T = sc.nextInt(); while (T-- > 0) { int N = sc.nextInt(); int M = sc.nextInt(); int R = sc.nextInt(); int[][] arr = new int[R][3]; for (int i = 0; i < R; i++) { for (int j = 0; j < 2; j++) { arr[i][j] = sc.nextInt(); } arr[i][2] = -sc.nextInt(); } Arrays.sort(arr, new Comparator<int[]>() { @Override public int compare(int[] o1, int[] o2) { return o1[2] - o2[2]; } }); long ans = 0; par = new int[N + M + 4]; rank = new int[N + M + 4]; final int cost = 10000; for (int i = 0; i < par.length; i++) { par[i] = i; } //kruskal for (int i = 0; i < R; i++) { int a = arr[i][0]; int b = arr[i][1]; if (same(a, b + N)) continue; unite(a, b + N); ans += arr[i][2]; } System.out.println(ans + (N + M) * cost); } } public static int findp(int x) { if (par[x] == x) return x; return par[x] = findp(par[x]); //return findp(par[x]) will make TLE } public static boolean same(int x, int y) { return findp(x) == findp(y); } public static void unite(int x, int y) { x = findp(x); y = findp(y); if (x == y) return ; if (rank[x] < y) { par[x] = y; } else { par[y] = x; if (rank[x] == rank[y]) rank[x]++; } } } class sc { static BufferedReader reader; static StringTokenizer tokenizer; /** call this method to initialize reader for InputStream */ static void init(InputStream input) { reader = new BufferedReader( new InputStreamReader(input) ); tokenizer = new StringTokenizer(""); } /** get next word */ static String next() throws IOException { while ( ! tokenizer.hasMoreTokens() ) { //TODO add check for eof if necessary tokenizer = new StringTokenizer( reader.readLine() ); } return tokenizer.nextToken(); } static int nextInt() throws IOException { return Integer.parseInt( next() ); } } Followed by: Post your reply here: |
All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator