結果
| 問題 |
No.2290 UnUnion Find
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2023-07-24 11:05:08 |
| 言語 | C#(csc) (csc 3.9.0) |
| 結果 |
AC
|
| 実行時間 | 312 ms / 2,000 ms |
| コード長 | 2,022 bytes |
| コンパイル時間 | 2,337 ms |
| コンパイル使用メモリ | 113,316 KB |
| 実行使用メモリ | 36,992 KB |
| 最終ジャッジ日時 | 2024-10-01 06:29:42 |
| 合計ジャッジ時間 | 21,845 ms |
|
ジャッジサーバーID (参考情報) |
judge5 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 1 |
| other | AC * 46 |
コンパイルメッセージ
Microsoft (R) Visual C# Compiler version 3.9.0-6.21124.20 (db94f4cc) Copyright (C) Microsoft Corporation. All rights reserved.
ソースコード
using System;
using static System.Console;
using System.Linq;
using System.Collections.Generic;
class Program
{
static int NN => int.Parse(ReadLine());
static int[] NList => ReadLine().Split().Select(int.Parse).ToArray();
static int[][] NArr(long n) => Enumerable.Repeat(0, (int)n).Select(_ => NList).ToArray();
public static void Main()
{
Solve();
}
static void Solve()
{
var c = NList;
var (n, q) = (c[0], c[1]);
var query = NArr(q);
var uf = new UnionFindTree(n);
var other = 1;
var ans = new List<int>();
foreach (var que in query)
{
if (que[0] == 1)
{
uf.Unite(que[1] - 1, que[2] - 1);
while (other < n && uf.IsSameTree(0, other)) ++other;
}
else
{
if (!uf.IsSameTree(0, que[1] - 1)) ans.Add(1);
else if (other < n) ans.Add(other + 1);
else ans.Add(-1);
}
}
WriteLine(string.Join("\n", ans));
}
class UnionFindTree
{
int[] roots;
public UnionFindTree(int size)
{
roots = new int[size];
for (var i = 0; i < size; ++i) roots[i] = -1;
}
public int GetRoot(int a)
{
if (roots[a] < 0) return a;
return roots[a] = GetRoot(roots[a]);
}
public bool IsSameTree(int a, int b)
{
return GetRoot(a) == GetRoot(b);
}
public bool Unite(int a, int b)
{
var x = GetRoot(a);
var y = GetRoot(b);
if (x == y) return false;
if (-roots[x] < -roots[y]) { var tmp = x; x = y; y = tmp; }
roots[x] += roots[y];
roots[y] = x;
return true;
}
public int GetSize(int a)
{
return -roots[GetRoot(a)];
}
}
}