Submission #1983826


Source Code Expand

import * as fs from "fs";

export class UnionFind {
	private _parent: Array<number>;
	private _rank: Array<number>;
	private _size: Array<number>;
	private _length: number;
	get length(): number {
		return this._length;
	}
	constructor(length: number) {
		this._length = length;
		this._parent = new Array(length);
		for (let i = 0; i < length; i++) {
			this._parent[i] = i;
		}
		this._rank = new Array(length).fill(1);
		this._size = new Array(length).fill(1);
	}
	root(node: number): number {
		const stack: Array<number> = [node];
		while (true) {
			const top = stack[stack.length - 1];
			const p = this._parent[top];
			if (p === top) {
				break;
			}
			else {
				stack.push(p);
			}
		}
		const result = stack.pop()!;
		while (stack.length > 0) {
			this._parent[stack.pop()!] = result;
		}
		return result;
	}
	size(node: number): number {
		return this._size[this.root(node)];
	}
	check(x: number, y: number): boolean {
		return this.root(x) === this.root(y);
	}
	unite(x: number, y: number) {
		x = this.root(x);
		y = this.root(y);
		if (this._rank[x] >= this._rank[y]) {
			this._parent[y] = this._parent[x];
			if (this._rank[x] === this._rank[y]) {
				this._rank[y] += 1;
			}
			this._size[x] += this._size[y];
		}
		else {
			this._parent[x] = this._parent[y];
			this._size[y] = this._size[x];
		}
		return 0;
	}
}

let input = (fs.readFileSync("/dev/stdin", "utf8") as string).split("\n");
const [n, m] = input[0].split(" ").map((x: string): number => +x);

const uf: UnionFind = new UnionFind(n);

for (let i = 0; i < m; i++) {
	const [a, b] = input[i + 1].split(" ").map((x: string): number => +x);
	uf.unite(a - 1, b - 1);
}

const set = new Set<number>();
for (let i = 0; i < n; i++) {
	set.add(uf.root(i));
}

console.log(set.size-1);

Submission Info

Submission Time
Task B - 道路工事
User tatamo
Language TypeScript (2.1.6)
Score 100
Code Size 1841 Byte
Status AC
Exec Time 219 ms
Memory 32688 KB

Judge Result

Set Name Sample All
Score / Max Score 0 / 0 100 / 100
Status
AC × 2
AC × 22
Set Name Test Cases
Sample sample1.txt, sample2.txt
All 0.txt, 1.txt, 10.txt, 11.txt, 12.txt, 13.txt, 14.txt, 15.txt, 16.txt, 17.txt, 18.txt, 19.txt, 2.txt, 3.txt, 4.txt, 5.txt, 6.txt, 7.txt, 8.txt, 9.txt, sample1.txt, sample2.txt
Case Name Status Exec Time Memory
0.txt AC 54 ms 7372 KB
1.txt AC 53 ms 7372 KB
10.txt AC 54 ms 7372 KB
11.txt AC 54 ms 7372 KB
12.txt AC 57 ms 7600 KB
13.txt AC 57 ms 7600 KB
14.txt AC 56 ms 7628 KB
15.txt AC 185 ms 30868 KB
16.txt AC 78 ms 20740 KB
17.txt AC 78 ms 20740 KB
18.txt AC 85 ms 20344 KB
19.txt AC 219 ms 32688 KB
2.txt AC 54 ms 7372 KB
3.txt AC 54 ms 7372 KB
4.txt AC 54 ms 7372 KB
5.txt AC 54 ms 7372 KB
6.txt AC 54 ms 7372 KB
7.txt AC 53 ms 7372 KB
8.txt AC 53 ms 7372 KB
9.txt AC 54 ms 7372 KB
sample1.txt AC 54 ms 7372 KB
sample2.txt AC 54 ms 7372 KB