結果
| 問題 |
No.1054 Union add query
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2020-05-16 10:44:49 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 186 ms / 2,000 ms |
| コード長 | 2,205 bytes |
| コンパイル時間 | 1,786 ms |
| コンパイル使用メモリ | 170,060 KB |
| 実行使用メモリ | 7,296 KB |
| 最終ジャッジ日時 | 2024-09-22 02:37:35 |
| 合計ジャッジ時間 | 4,268 ms |
|
ジャッジサーバーID (参考情報) |
judge2 / judge4 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 8 |
ソースコード
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); i ++)
using namespace std;
typedef long long ll;
typedef pair<ll,ll> PL;
typedef pair<int,int> P;
const int INF = 1e9;
const int MOD = 17;
const vector<int> dy = {-1,0,1,0};
const vector<int> dx = {0,1,0,-1};
struct UnionFind {
int N;
vector<int> parents;
vector<int> count;
UnionFind(int _N) : N(_N){
parents = vector<int>(N,-1);
count = vector<int>(N,0);
}
int find(int x) { //xの親を返す
if (parents[x] < 0) return x;
else {
int p = find(parents[x]);
return p;
}
}
void unite(int x, int y) { //xとyの含むグループを併合
int px = find(x);
int py = find(y);
if (parents[px] > parents[py]) swap(px,py);
if (px != py) {
parents[px] += parents[py];
count[py] -= count[px];
parents[py] = px;
}
}
bool same(int x, int y) { //x,yが同じグループにいるか判定
return find(x) == find(y);
}
int size(int x) { //xと同じグループのメンバーの個数
return parents[find(x)];
}
vector<int> root() {//ufの根を列挙
vector<int> res;
for (int i = 0; i < N; i ++) {
if (parents[i] < 0) res.push_back(i);
}
return res;
}
int group_count() { //ufのグループの数を数える
int cnt = 0;
for (int i = 0; i < N; i ++) {
if (parents[i] < 0) cnt ++;
}
return cnt;
}
void add(int x,int a) {
int p = find(x);
count[p] += a;
}
int calc(int x) {
if (parents[x] < 0) return count[x];
int ans = calc(parents[x]);
return ans + count[x];
}
};
int main() {
int N,Q; scanf("%d %d",&N,&Q);
UnionFind uf(N);
rep(i,Q) {
int t,a,b; scanf("%d %d %d",&t,&a,&b);
if (t == 1) {
a --; b--;
uf.unite(a,b);
}
else if (t == 2) {
a --;
uf.add(a,b);
}
else {
a --;
printf("%d\n",uf.calc(a));
}
}
}