洛谷 P1194 买礼物 (Kruskal)

Click is the Problem
洛谷的题感觉判的比较严,AcWing的模板还要再加修改才能过。

这个题题面看上去不知道在说啥,样例也不好理解。如果看出是最短路就是一道模板题了,还是有点难度的。

i 对 j 有优惠则建边,跑一遍kruskal即可。

import java.io.*;
import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.StringTokenizer;

public class Main {

	static class InputReader {
		public BufferedReader Reader;
		public StringTokenizer tokenizer;

		public InputReader(InputStream stream) {
			Reader = new BufferedReader(new InputStreamReader(System.in), 32768);
			tokenizer = null;
		}

		public String next() {
			while (tokenizer == null || !tokenizer.hasMoreTokens()) {
				try {
					tokenizer = new StringTokenizer(Reader.readLine());
				} catch (IOException e) {
					throw new RuntimeException(e);
				}
			}
			return tokenizer.nextToken();
		}

		public int nextInt() {
			return Integer.parseInt(next());
		}

		public long nextLong() {
			return Long.parseLong(next());
		}

		public float nextFloat() {
			return Float.parseFloat(next());
		}

		public double nextDouble() {
			return Double.parseDouble(next());
		}
	}

	static InputReader in = new InputReader(System.in);
	static PrintWriter out = new PrintWriter(System.out);
	///
	static int N = 200010, A, B;
	static int p[] = new int[N];
	static Edge e[] = new Edge[N];

	public static void main(String[] args) throws IOException {

		A = in.nextInt();
		B = in.nextInt();
		int k = 0;

		for (int i = 1; i <= B; i++) {
			p[i] = i;
		}

		for (int i = 1; i <= B; i++) {
			for (int j = 1; j <= B; j++) {
				int x = in.nextInt();
				if (x != 0 && i <= j)
					e[k++] = new Edge(i, j, x);
			}
		}

		Arrays.sort(e, 0, k);
		

		int res = 0;
		for (int i = 0; i < k; i++) {
			int a = e[i].a;
			int b = e[i].b;
			int c = e[i].c;
			int xa = find(a);
			int xb = find(b);
			if (xa != xb) {
				p[xa] = xb;
				res += Math.min(A, e[i].c);
			}
		}

		out.println(res + A);

		out.flush();
	}

	public static int find(int x) {
		if (p[x] != x)
			p[x] = find(p[x]);
		return p[x];

	}

}

class Edge implements Comparable<Edge> {
	int a, b, c;

	public Edge(int a, int b, int c) {
		super();
		this.a = a;
		this.b = b;
		this.c = c;
	}

	@Override
	public int compareTo(Edge temp) {
		// TODO Auto-generated method stub
		return this.c - temp.c;
	}

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值