結果
| 問題 |
No.1166 NADA DNA
|
| ユーザー |
tenten
|
| 提出日時 | 2021-11-24 15:43:51 |
| 言語 | Java (openjdk 23) |
| 結果 |
AC
|
| 実行時間 | 463 ms / 3,000 ms |
| コード長 | 3,071 bytes |
| コンパイル時間 | 2,598 ms |
| コンパイル使用メモリ | 78,532 KB |
| 実行使用メモリ | 72,896 KB |
| 最終ジャッジ日時 | 2024-06-27 01:06:01 |
| 合計ジャッジ時間 | 11,600 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge2 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 20 |
ソースコード
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner();
int n = sc.nextInt();
int length = sc.nextInt();
char[][] dnas = new char[n][];
for (int i = 0; i < n; i++) {
dnas[i] = sc.next().toCharArray();
}
PriorityQueue<Path> queue = new PriorityQueue<>();
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int count = 0;
for (int k = 0; k < length; k++) {
if (dnas[i][k] != dnas[j][k]) {
count++;
}
}
queue.add(new Path(count, i, j));
}
}
int ans = 0;
UnionFindTree uft = new UnionFindTree(n);
while (queue.size() > 0) {
Path p = queue.poll();
if (uft.same(p)) {
continue;
}
ans += p.cost;
uft.unite(p);
}
System.out.println(ans);
}
static class UnionFindTree {
int[] parents;
public UnionFindTree(int size) {
parents = new int[size];
for (int i = 0; i < size; i++) {
parents[i] = i;
}
}
public int find(int x) {
if (x == parents[x]) {
return x;
} else {
return parents[x] = find(parents[x]);
}
}
public boolean same(int x, int y) {
return find(x) == find(y);
}
public boolean same(Path p) {
return same(p.left, p.right);
}
public void unite(int x, int y) {
if (!same(x, y)) {
parents[find(y)] = find(x);
}
}
public void unite(Path p) {
unite(p.left, p.right);
}
}
static class Path implements Comparable<Path> {
int cost;
int left;
int right;
public Path(int cost, int left, int right) {
this.cost = cost;
this.left = left;
this.right = right;
}
public int compareTo(Path another) {
return cost - another.cost;
}
}
}
class Scanner {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer("");
public Scanner() throws Exception {
}
public int nextInt() throws Exception {
return Integer.parseInt(next());
}
public long nextLong() throws Exception {
return Long.parseLong(next());
}
public double nextDouble() throws Exception {
return Double.parseDouble(next());
}
public String next() throws Exception {
if (!st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
}
tenten