結果
問題 |
No.2290 UnUnion Find
|
ユーザー |
![]() |
提出日時 | 2023-05-10 17:12:05 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 460 ms / 2,000 ms |
コード長 | 1,906 bytes |
コンパイル時間 | 3,827 ms |
コンパイル使用メモリ | 259,088 KB |
最終ジャッジ日時 | 2025-02-12 21:13:43 |
ジャッジサーバーID (参考情報) |
judge5 / judge3 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 1 |
other | AC * 46 |
ソースコード
#include <bits/stdc++.h> #include <atcoder/all> using namespace std; using namespace atcoder; using ll=long long; using ld=long double; ld pie=3.141592653589793; ll inf=14449999999999999; ll mod=998244353; struct unionfind { vector<ll>par,siz; unionfind(ll n): par(n,-1),siz(n,1){} ll root(ll x){ if (par[x]==-1) { return x; }else{ return par[x]=root(par[x]); } } bool issame(ll x,ll y){ return root(x)==root(y); } bool unite(ll x,ll y){ x=root(x); y=root(y); if (x==y) { return false; } if (siz[x]<siz[y]) { swap(x,y); } par[y]=x; siz[x]+=siz[y]; return true; } ll size(ll x){ return siz[root(x)]; } }; int main(){ ll n,q; cin >> n >> q; unionfind uf(n); set<ll>s; for (ll i = 0; i < n; i++) { s.insert(i); } s.insert(-1); s.insert(inf); vector<ll>ans; for (ll i = 0; i < q; i++) { ll t; cin >> t; if (t==1) { ll u,v; cin >> u >> v; u--,v--; if (!uf.issame(u,v)) { s.erase(uf.root(u)); s.erase(uf.root(v)); uf.unite(u,v); s.insert(uf.root(u)); } }else{ ll v; cin >> v; v--; auto x=s.lower_bound(uf.root(v)); auto y=prev(x); auto z=next(x); if (*(y)!=-1) { ans.push_back(*(y)); }else if (*(z)!=inf) { ans.push_back(*(z)); }else{ ans.push_back(-2); } } } for (ll i = 0; i < ans.size(); i++) { cout << ans[i]+1 << endl; } }