[JSOI2008] Star Wars starwar BZOJ1015

and check

The time complexity of positive order processing is n^2, considering reverse order processing, in this way, the time complexity is reduced from n^2 to nlogn

Attached code:

#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <queue>
using namespace std;
#define N 400005
int fa[N<<1],n,m,K,head[N<<1],cnt,q[N],ans[N];
struct node
{
	int to,next;
}e[N<<1];
void add(int x,int y)
{
	e [cnt] .to = y;
	e[cnt].next=head[x];
	head[x]=cnt++;
	return ;
}
int find(int x)
{
	int p=x,t;
	while (fa [p]! = p) p = fa [p];
	while(x!=p)t=fa[x],fa[x]=p,x=t;
	return p;
}
bool fish [N];
intmain()
{
	for(int i=1;i<N;i++)fa[i]=i;
	memset(head,-1,sizeof(head));
	memset(vis,1,sizeof(vis));
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++)
	{
		int x,y;
		scanf("%d%d",&x,&y);
		x++,y++;
		add(x,y);
		add(y,x);
	}
	scanf("%d",&K);
	ans[K]=nK;
	for(int i=1;i<=K;i++)
	{
		scanf("%d",&q[i]);
		q[i]++;
		force[q[i]]=0;
	}
	for(int i=1;i<=n;i++)
	{
		if(!vis[i])continue;
		for(int j=head[i];j!=-1;j=e[j].next)
		{
			int to1=e[j].to;
			if(!vis[to1])continue;
			int fx=find(i),fy=find(to1);
			if(fx!=fy)
			{
				fa [fx] = fy;
				years[K]--;
			}
		}
	}
	force[q[K]]=1;
	for(int i=K-1;i>=0;i--)
	{
		years[i]=years[i+1]+1;
		for(int j=head[q[i+1]];j!=-1;j=e[j].next)
		{
			int to1=e[j].to;
			if(!vis[to1])continue;
			int fx=find(q[i+1]),fy=find(to1);
			if(fx!=fy)
			{
				fa [fx] = fy;
				years[i]--;
			}
		}
		force[q[i]]=1;
	}
	for(int i=0;i<=K;i++)
	{
		printf("%d\n",ans[i]);
	}
	return 0;
}

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325694433&siteId=291194637