# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
202109 | awlintqaa | Zamjene (COCI16_zamjene) | C++14 | 0 ms | 0 KiB |
This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#define fast ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#include <bits/stdc++.h>
using namespace std;
#define sqr 340
#define mid (l+r)/2
#define pb push_back
#define ppb pop_back
#define fi first
#define se second
#define lb lower_bound
#define ub upper_bound
#define ins insert
#define era erase
#define C continue
#define mem(dp,i) memset(dp,i,sizeof(dp))
#define mset multiset
typedef long long ll;
typedef short int si;
typedef long double ld;
typedef pair<int,int> pi;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<pi> vpi;
typedef vector<pll> vpll;
const ll inf=1e18*4;
const ld pai=acos(-1);
const int MX = 1e6+9;
ll n,q,ans;
ll H=1234577,po[MX];
ll a[MX],b[MX];
ll hasha[MX],hashb[MX];
ll p[MX],sz[MX];
map<ll,ll>num;
ll get(ll node){
if(p[node]==node)return node;
return p[node]=get(p[node]);
}
void add_nodes(ll seg,ll dif,ll N){
if(dif!=0){
ans+=seg*num[-dif]*N;
}
num[dif]+=seg*N;
}
void merge(ll a,ll b){
a=get(a);
b=get(b);
if(a==b)return ;
add_nodes(-1,hasha[a]-hashb[a],sz[a]);
add_nodes(-1,hasha[b]-hashb[b],sz[b]);
p[b]=a;
hasha[a]+=hasha[b];
hashb[a]+=hashb[b];
sz[a]+=sz[b];
add_nodes(1,hasha[a]-hashb[a],sz[a]);
}
void add(int sgn, int u, int pos, int value) {
hashb[u] += sgn * po[pos];
hasha[u] += sgn * po[value];
sz[u] += sgn;
}
int main(){
cin>>n>>q;
po[0]=1;
for(ll i=1;i<=MX;i++)po[i]=po[i-1]*H;
for(ll i=0;i<n;i++)cin>>a[i],b[i]=a[i];
sort(b,b+n);
for(ll i=0;i<n;i++){
p[i]=i,sz[i]=1;
hasha[i]=po[a[i]];
hashb[i]=po[b[i]];
add_nodes(1,hasha[i]-hashb[i],1);
}
while(q--){
ll t;cin>>t;
if(t==1){
ll x,y;
cin>>x>>y;
x--,y--;
ll X=get(x);
ll Y=get(y);
if(X==Y){
swap(a[x],a[y]);
C;
}
add_nodes(-1,hasha[X]-hashb[X],sz[X]);
add_nodes(-1,hasha[Y]-hashb[Y],sz[y]);
edit(-1,X,x,a[x]);
edit(-1,Y,y,a[y]);
swap(a[x],a[y]);
edit(1,X,x,a[x]);
edit(1,Y,y,a[y]);
add_nodes(1,hasha[X]-hashb[X],sz[X]);
add_nodes(1,hasha[Y]-hashb[Y],sz[Y]);
}
else if(t==2){
ll x,y;
cin>>x>>y;
x--,y--;
merge(x,y);
}
else if(t==3){
if(num[0]==n)cout<<"DA"<<endl;
else cout<<"NE"<<endl;
}
else if(t==4){
cout<<ans<<endl;
}
}
}