結果
| 問題 |
No.2563 色ごとのグループ
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2023-12-02 15:03:48 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 742 ms / 2,000 ms |
| コード長 | 2,114 bytes |
| コンパイル時間 | 2,488 ms |
| コンパイル使用メモリ | 78,816 KB |
| 実行使用メモリ | 67,868 KB |
| 最終ジャッジ日時 | 2024-09-26 17:58:45 |
| 合計ジャッジ時間 | 14,373 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 35 |
ソースコード
import java.util.*;
import java.io.*;
class Main{
private static final BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
private static final PrintWriter out =
new PrintWriter(System.out);
public static void main(String[] args)throws IOException{
String[] str = br.readLine().split(" ");
int N = Integer.parseInt(str[0]);
int M = Integer.parseInt(str[1]);
int[] C = new int[N];
str = br.readLine().split(" ");
for(int i=0;i<N;i++)
C[i] = Integer.parseInt(str[i]);
HashMap<Integer,int[]> map = new HashMap<>();
for(int i=0;i<N;i++){
if(map.containsKey(C[i]))
map.get(C[i])[1]++;
else
map.put(C[i],new int[]{0,1});
}
UnionFind uf = new UnionFind(N+1);
while(M-->0){
str = br.readLine().split(" ");
int u = Integer.parseInt(str[0]);
int v = Integer.parseInt(str[1]);
if(C[u-1]==C[v-1])
if(uf.unite(u,v))
map.get(C[u-1])[0]++;
}
int ans = 0;
for(int[] temp:map.values())
ans += temp[1]-temp[0]-1;
out.println(ans);
br.close();
out.close();
}
}
final class UnionFind {
private final int[] par, rank, size, path;
private int count;
public UnionFind ( final int N ) {
count = N;
par = new int[N];
rank = new int[N];
size = new int[N];
path = new int[N];
Arrays.fill( par, -1 );
Arrays.fill( size, 1 );
}
public int root ( final int ind ) {
if ( par[ind] == -1 ) {
return ind;
}
else {
return par[ind] = root( par[ind] );
}
}
public boolean isSame ( final int x, final int y ) {
return root( x ) == root( y );
}
public boolean unite ( final int x, final int y ) {
int rx = root( x );
int ry = root( y );
++path[rx];
if ( rx == ry ) {
return false;
}
if ( rank[rx] < rank[ry] ) {
int temp = rx;
rx = ry;
ry = temp;
}
par[ry] = rx;
if ( rank[rx] == rank[ry] ) {
++rank[rx];
}
path[rx] += path[ry];
size[rx] += size[ry];
--count;
return true;
}
public int groupCount () {
return count;
}
public int pathCount ( final int x ) {
return path[root( x )];
}
public int size ( final int x ) {
return size[root( x )];
}
}