跳到正文

算法·理论

听课笔记

xcgmy约 2 分钟
原文

这是 2026年11月21日 存档的第 3 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年11月12日
收录
2026年11月17日
更新
2026年11月28日
篇幅
约 2 分钟
获赞
1

版本

  1. v5当前
  2. v4
  3. v3
  4. v2
更早的 1 个版本
  1. v1

2026.11.17

并查集:有根有向的树形结构

主要内容:带权并查集——边带权值

例题:P1892 团伙 使用带权并查集维护与其他节点的关系,异或求

CodeCode

暂时错误
C++
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+6;
int n,m,fa[maxn],w[maxn];
struct node{
	int root,flag;
};
node find(int x){
	if(fa[x]==x) return(node){x,0};
	node nw=find(fa[x]);
	w[x]=w[x]^nw.flag;
	nw.flag=w[x];
	return nw;
}
void unite(int x,int y,int op){
	node fx=find(x),fy=find(y);
	if(fx.root==fy.root) return;
	w[fx.root]=fx.flag^fy.flag^op;
	fa[fx.root]=fy.root;
}
int main(){
	cin>>n>>m;
	for(int i=1;i<=n;i++) fa[i]=i,w[i]=0;
	while(m--){
		char op;
		int p,q;
		cin>>op>>p>>q;
		if(op=='F') unite(p,q,0);
		else unite(p,q,1);
	}
	set<int> st;
	for(int i=1;i<=n;i++) st.insert(find(i).root);
	cout<<st.size()<<endl;
	return 0;
}//但是我不知道怎么WA了QwQ

二项式定理:自己查资料后补充,现在暂时还不会