結果

問題 No.748 yuki国のお財布事情
ユーザー 37zigen37zigen
提出日時 2020-04-01 16:13:25
言語 Java
(openjdk 23)
結果
AC  
実行時間 1,007 ms / 2,000 ms
コード長 1,753 bytes
コンパイル時間 2,688 ms
コンパイル使用メモリ 79,860 KB
実行使用メモリ 58,984 KB
最終ジャッジ日時 2024-06-26 22:45:37
合計ジャッジ時間 16,558 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.util.Arrays;
import java.util.PriorityQueue;
import java.util.Scanner;

class DJSet{
	int n;
	int[] upper;
	
	public DJSet(int n) {
		this.n=n;
		upper=new int[n];
		Arrays.fill(upper, -1);
	}

	int root(int x) {
		return upper[x]<0?x:(upper[x]=root(upper[x]));
	}
	
	boolean equiv(int x,int y) {
		return root(x)==root(y);
	}
	
	void setUnion(int x,int y) {
		x=root(x);y=root(y);
		if(x==y)return;
		if(upper[x]<upper[y]) {
			x^=y;y^=x;x^=y;
		}
		if(upper[x]==upper[y])--upper[y];
		upper[x]=y;
	}
}

class Edge implements Comparable<Edge>{
	int src,dst,cost;
	
	public Edge(int src,int dst,int cost) {
		this.src=src;
		this.dst=dst;
		this.cost=cost;
	}
	@Override
	public int compareTo(Edge o) {
		return cost-o.cost;
	}
}

class Main {
	public static void main(String[] args) {
		new Main().run();
	}
	
	void run() {
		Scanner sc=new Scanner(System.in);
		int N=sc.nextInt();
		int M=sc.nextInt();
		int K=sc.nextInt();
		DJSet ds=new DJSet(N);
		PriorityQueue<Edge> pq=new PriorityQueue<>();
		int[] a=new int[M];
		int[] b=new int[M];
		int[] c=new int[M];
		boolean[] fixed=new boolean[M];
		for(int i=0;i<M;++i) {
			a[i]=Integer.parseInt(sc.next());
			b[i]=Integer.parseInt(sc.next());
			c[i]=Integer.parseInt(sc.next());
			--a[i];--b[i];
		}
		long ans=0;
		for(int i=0;i<K;++i) {
			int e=Integer.parseInt(sc.next());
			--e;
			ds.setUnion(a[e], b[e]);
			fixed[e]=true;
		}
		for(int i=0;i<M;++i) if(!fixed[i]) pq.add(new Edge(a[i], b[i], c[i]));
		while(!pq.isEmpty()) {
			Edge e=pq.poll();
			if(ds.equiv(e.src, e.dst)) {
				ans+=e.cost;
			}else {
				ds.setUnion(e.src, e.dst);
			}
		}
		System.out.println(ans);
	}
	
	static void tr(Object... objects) {
		System.out.println(Arrays.deepToString(objects));
	}

}

0