Submission #255558

#TimeUsernameProblemLanguageResultExecution timeMemory
255558Vladikus004Zamjene (COCI16_zamjene)C++14
140 / 140
3039 ms187728 KiB
#include <bits/stdc++.h> #define inf 2e9 #define all(v) v.begin(), v.end() using namespace std; typedef long long ll; typedef long double ld; typedef pair <int, int> pii; mt19937_64 rnd(time(0)); const int N = 1000000 + 3; int n, q, sz[N], a[N], b[N], p[N], cnt, ans3; ll sum[N], nsum[N], ans; unordered_map <ll, int> mp; map <int, ll> code; void init(){ for (int i = 0; i < N; i++) code[i] = rnd(); for (int i = 0; i < n; i++){ p[i] = i; sz[i] = 1; sum[i] = code[a[i]]; nsum[i] = code[b[i]]; if (sum[i] != nsum[i]){ ans += mp[nsum[i] - sum[i]]; mp[sum[i] - nsum[i]]++; }else ans3++; } } int get_anc(int x){ if (p[x] == x) return x; return p[x] = get_anc(p[x]); } void er(int x){ if (nsum[x] != sum[x]){ ans -= mp[nsum[x] - sum[x]] * sz[x]; mp[sum[x] - nsum[x]] -= sz[x]; }else ans3--; } void add(int x){ if (nsum[x] != sum[x]){ ans += mp[nsum[x] - sum[x]] * sz[x]; mp[sum[x] - nsum[x]] += sz[x]; }else ans3++; } void unite(int x, int y){ int px = get_anc(x); int py = get_anc(y); if (px == py) return; cnt--; er(px); er(py); if (sz[px] < sz[py]) swap(px, py); p[py] = px; sz[px] += sz[py]; sum[px] += sum[py]; nsum[px] += nsum[py]; add(px); } void sw(int x, int y){ int px = get_anc(x); int py = get_anc(y); if (px == py) { swap(a[x], a[y]); return; } er(px); er(py); sum[px] += code[a[y]] - code[a[x]]; sum[py] += code[a[x]] - code[a[y]]; add(px); add(py); swap(a[x], a[y]); } int main() { ios_base::sync_with_stdio(false); cin.tie(0); #ifdef LOCAL freopen("input.txt", "r", stdin); #endif // LOCAL cin >> n >> q; for (int i = 0; i < n; i++) { cin >> a[i]; b[i] = a[i]; } sort(b, b + n); init(); cnt = n; for (int i = 0; i < q; i++){ int tp, x, y; cin >> tp; if (tp == 1){ cin >> x >> y; --x; --y; sw(x, y); }else if (tp == 2){ cin >> x >> y; --x; --y; unite(x, y); }else if (tp == 3){ if (cnt==ans3) cout << "DA\n"; else cout << "NE\n"; }else{ cout << ans << "\n"; } } }
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...