洛谷提高试炼场 并查集

修复公路

 

#include
#include
#include
using namespace std;
int n,m,fa[200000],flag;
struct edge{
	int from;
	int to;
	int v;
}a[100020]; 
int cmp(const edge &x,const edge &y)
 {
 	return x.v>n>>m;
	for(int i=1;i<=n;i++) fa[i]=i;
	for(int i=1;i<=m;i++) cin>>a[i].from>>a[i].to>>a[i].v;
	sort(a+1,a+m+1,cmp);
	for(int i=1;i<=m;i++){
		fa[find(a[i].to)]=find(a[i].from);
		if(judge()==1){
			cout<

食物链

#include
#include
using namespace std;
int n,m,ans,k;
int flag,x1,y1,fa[180000];
int find(int x){
	if(x==fa[x]) return x;
	fa[x]=find(fa[x]);
	return fa[x];
}
void get(int x,int y){
	int xx=find(x),yy=find(y);
	fa[xx]=yy;
}
int main(){
	cin>>n>>k;
	for(int i=1;i<=3*n;i++) fa[i]=i;
	for(int i=1;i<=k;i++)
	 {
	 	cin>>flag>>x1>>y1;
	 	if(flag==2&&x1==y1){ans++;continue;} 
	 	if(x1>n||y1>n){ans++;continue;}
		if(flag==1){
		   if(find(x1+n)==find(y1)||find(x1+2*n)==find(y1)){ans++;continue;}
		   get(x1,y1);get(x1+n,y1+n);get(x1+2*n,y1+2*n);	
		}
		if(flag==2){
		   if(find(x1)==find(y1)||find(x1+2*n)==find(y1)){ans++;continue;}
		    get(x1+n,y1);get(x1+2*n,y1+n);get(x1,y1+2*n);	
		}
	 }
	 cout<

星球大战 

#include
#include
#include
#include
#include 
#pragma GCC optimize(2)
#pragma GCC optimize(3)
using namespace std;
inline char nc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline int read(){
    char ch=nc();int sum=0;
    while(!(ch>='0'&&ch<='9'))ch=nc();
    while(ch>='0'&&ch<='9')sum=sum*10+ch-48,ch=nc();
    return sum;
}
const int N=400007;
int top,sum[N],n,m,head[N],next[N],to[N],num,a[N],from[N],fl[N],fa[N];
inline void add(int x,int y){
    num++;
    to[num]=y;
    from[num]=x;
    next[num]=head[x];
    head[x]=num;
}
inline int find(int x){
    if(x==fa[x]) return x;
    return fa[x]=find(fa[x]);
}
int main(){
    n=read();m=read();	
    int x,y;
    for(register int i=1;i<=m;i++){
        x=read();y=read();
        add(x,y);add(y,x);
    }
    int k=read();
    for(register int i=1;i<=k;i++) a[i]=read(),fl[a[i]]=1;
    int ans=n-k;
    for(register int i=0;i<=n-1;i++) fa[i]=i;
    for(register int i=1;i<=2*num;i++){
        if(!fl[from[i]]&&!fl[to[i]]){
            int x=find(from[i]),y=find(to[i]);
            if(x!=y) ans--,fa[x]=y;
        }
    }
    sum[1]=ans;
    top=1;
    for(register int i=k;i>=1;i--){
        fl[a[i]]=0;
        ans++;
        for(register int j=head[a[i]];j;j=next[j]){
            if(!fl[from[j]]&&!fl[to[j]]){
                int x=find(from[j]),y=find(to[j]);
                if(x!=y) ans--,fa[x]=y; 
            }
        }
        top++;
        sum[top]=ans;
    }
    for(register int i=top;i>=1;i--){
        printf("%d\n",sum[i]);
    }
    return 0;
} 

 

你可能感兴趣的:(编程)