Submission #1338205

#TimeUsernameProblemLanguageResultExecution timeMemory
1338205boclobanchatMaking Friends on Joitter is Fun (JOI20_joitter2)C++20
0 / 100
8 ms14404 KiB
#include<bits/stdc++.h>
using namespace std;
const int MAXN=3e5+5;
set<int> st[MAXN];
//map< pair<int,int>,vector<int> > mp;
multiset< pair<int,int> > sus;
int Q[MAXN][2],pq[MAXN][2],dsu[MAXN],sum[MAXN],cnt[MAXN];
vector< pair<int,int> > vi[MAXN];
bool ck[MAXN];
long long ans=0;
int root(int i)
{
	if(!dsu[i]) return i;
	return dsu[i]=root(dsu[i]);
}
void merge(int i,int j)
{
	if((i=root(i))==(j=root(j))) return ;
	if(vi[i].size()<vi[j].size()) swap(i,j);
	ans-=1LL*cnt[i]*(cnt[i]-1)+1LL*cnt[j]*(cnt[j]-1);
	ans-=1LL*cnt[i]*st[i].size()+1LL*cnt[j]*st[j].size();
	for(auto v:vi[j]) if(ck[v.first])
	{
		sus.erase(sus.lower_bound({Q[v.first][0],Q[v.first][1]}));
		st[Q[v.first][1]].erase(pq[v.first][0]);
		Q[v.first][v.second]=i;
		if(Q[v.first][0]!=Q[v.first][1])
		{
			if(st[Q[v.first][1]].find(pq[v.first][0])==st[Q[v.first][1]].end())
				st[Q[v.first][1]].insert(pq[v.first][0]),sus.insert({Q[v.first][0],Q[v.first][1]});
			else ck[v.first]=false;
		}
		else ck[v.first]=false;
		vi[i].push_back(v);
	}
	vi[j].clear(),dsu[j]=i,cnt[i]+=cnt[j],ans+=1LL*cnt[i]*(cnt[i]-1)+1LL*cnt[i]*st[i].size();
}
int main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);
	int n,q;
	cin>>n>>q;
	for(int i=1;i<=n;i++) cnt[i]=1;
	for(int i=1;i<=q;i++)
	{
		cin>>Q[i][0]>>Q[i][1];
		pq[i][0]=Q[i][0],pq[i][1]=Q[i][1];
		ck[i]=true;
	}
	for(int i=1;i<=q;i++)
	{
		int a=Q[i][0]=root(Q[i][0]),b=Q[i][1]=root(Q[i][1]);
		if(a!=b)
		{
			vi[a].push_back({i,0});
			vi[b].push_back({i,1});
			sus.insert({a,b});
			if(st[b].find(pq[i][0])==st[b].end()) ans+=cnt[b],st[b].insert(pq[i][0]);
			else ck[i]=false;
			if(sus.find({b,a})!=sus.end()) merge(a,b);
		}
		cout<<ans<<"\n";
	}
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...