并查集+

好久以前梁老讲的课了,一直没写笔记

并查集的基础应用
• 判断连通性
• 维护集合信息
• 合并序列区间
• 完成一些链表的操作

优化kruscal

实际上就是路径压缩:

int getfather(int x){
	return (father[x]==x)?father[x]:getfather(father[x]);
}

这样实现搜索路径压缩

和按秩合并(秩,每个根节点的叶子节点最深深度,用rank表示):

int merge/*合并*/(int x,int y){
   x=getfather(x);
   y=getfather(y);
   if(rank[x]<rank[y])swap(x,y);
   father[y]=x;
   if(rank[x]==rank[y])rank[x]++;
} 

这样使树尽量向满树靠拢,减少树的深度

欧拉图问题

一笔画问题,小学时的噩梦
但是现在看来就很简单

笔画数=(奇数度数数)%2
注意一个图里面可能会有多个连通分量
所以才要用并查集求出来

code(但是我不知道为什么这个在WOJ上会T)

#include<bits/stdc++.h>
using namespace std;
#define in Read()
#define re register
const int NNN=(int)1e5;
int n,m;
int degree[NNN],rank[NNN],father[NNN];
int cnt;
int num[NNN],odd[NNN];//必须要统计每个根节点的总儿子个数,以防它是个孤点,0笔画成 

inline int in{
	int i=0,f=1;char ch;
	while((ch>'9'||ch<'0')&&ch!='-')ch=getchar();
	if(ch=='-')f=-1,ch=getchar();
	while(ch<='9'&&ch>='0')i=(i<<1)+(i<<3)+ch-48,ch=getchar();
	return i*f;
}

inline int getfather(int x){
	return father[x]=(father[x]==x)?x:getfather(father[x]);
}

inline void merge(int x,int y){
	x=getfather(x);
	y=getfather(y);
	if(x==y)return ;
	if(rank[x]<rank[y])swap(x,y);
	father[y]=x;
	if(rank[y]==rank[x])rank[x]++;
	return ;
}

inline void Reset(int n){
	for(re int i=1;i<=n;i++)father[i]=i;
	cnt=0;
	memset(rank,0,sizeof(rank));
	memset(degree,0,sizeof(degree));
	memset(num,0,sizeof(num));
	memset(odd,0,sizeof(odd));
}

int main(){
	while(1){
		
		n=in,m=in;
		Reset(n);
		for(re int i=1;i<=m;i++){
			int u=in,v=in;
			degree[u]++,degree[v]++;
			merge(u,v);
		}
		
		for(re int i=1;i<=n;i++){
			int f=getfather(i);
			num[f]++;
			if(degree[i]%2)odd[f]++;
		}
		
		for(re int i=1;i<=n;i++){
			if(num[i]<=1)continue;
			else if(odd[i]==0)cnt++;
			else if(odd[i]>0)cnt+=odd[i]/2;
		}
		
		printf("%d\n",cnt);
	}
	return 0;
}

练习:银河英雄传说(NOI2002)萌萌哒(SCOI2016)

发布了26 篇原创文章 · 获赞 3 · 访问量 895

猜你喜欢

转载自blog.csdn.net/Antimonysbguy/article/details/104019475