結果
| 問題 | No.1054 Union add query |
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2020-05-15 22:00:51 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 153 ms / 2,000 ms |
| コード長 | 2,163 bytes |
| コンパイル時間 | 1,672 ms |
| コンパイル使用メモリ | 170,144 KB |
| 実行使用メモリ | 14,976 KB |
| 最終ジャッジ日時 | 2024-09-19 10:26:38 |
| 合計ジャッジ時間 | 3,984 ms |
|
ジャッジサーバーID (参考情報) |
judge1 / judge5 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 3 |
| other | AC * 8 |
ソースコード
#include <vector>
#include <tuple>
#include <iostream>
using std::cout;
using std::endl;
using i64 = long long;
struct union_find {
std::vector<int> par;
std::vector<i64> Sigma;
union_find(int N): par(N * 2, -1) , Sigma(N * 2, 0) {
}
int root(int x) {
if(par[x] < 0) {
return x;
}
int v = x;
while(par[par[v]] >= 0) {
v = par[v];
Sigma[x] += Sigma[v];
}
par[x] = par[v];
return par[v];
}
std::tuple<int, int> unite(int x, int y) {
x = root(x);
y = root(y);
if(x == y) return { -1, -1 };
if(par[x] > par[y]) std::swap(x, y);
par[x] += par[y];
par[y] = x;
Sigma[y] -= Sigma[x];
return { x, y };
}
void add(int v, i64 a) {
Sigma[root(v)] += a;
}
i64 value(int v) {
int r = root(v);
if(r == v) {
return Sigma[v];
}
else {
return Sigma[v] + Sigma[r];
}
}
};
#include <bits/stdc++.h>
using namespace std;
using i64 = long long;
#define rep(i,s,e) for(i64 (i) = (s);(i) < (e);(i)++)
#define all(x) x.begin(),x.end()
template<class T>
static inline std::vector<T> ndvec(size_t&& n, T val) noexcept {
return std::vector<T>(n, std::forward<T>(val));
}
template<class... Tail>
static inline auto ndvec(size_t&& n, Tail&&... tail) noexcept {
return std::vector<decltype(ndvec(std::forward<Tail>(tail)...))>(n, ndvec(std::forward<Tail>(tail)...));
}
template<class T, class Cond>
struct chain {
Cond cond; chain(Cond cond) : cond(cond) {}
bool operator()(T& a, const T& b) const {
if(cond(a, b)) { a = b; return true; }
return false;
}
};
template<class T, class Cond>
chain<T, Cond> make_chain(Cond cond) { return chain<T, Cond>(cond); }
int main() {
std::cin.tie(nullptr);
std::ios::sync_with_stdio(false);
int N, Q;
cin >> N >> Q;
union_find uf(N);
while(Q--) {
int t, a, b;
cin >> t >> a >> b;
a--;
if(t == 1) {
b--;
uf.unite(a, b);
}
else if(t == 2) {
uf.add(a, b);
}
else {
cout << uf.value(a) << "\n";
}
/*
cout << Q << endl;
rep(i,0,N) {
cout << i << " = " << uf.Sigma[i] << " " << uf.par[i] << endl;
}*/
}
}