跳到正文

题解

题解:CF1411C Peaceful Rooks

#SUSPENDED#约 2 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 2 分钟
题目
CF1411C

版本

  1. v1当前

CF1411C Peaceful Rooks

第一次写题解,管理大大求过


Solution

并查集:

·并查集,将车的行列坐标绑定(等于标记(x,x),(y,y)不能走,需要多移动一步),最后寻找根,若他们根相同,则需移动步数+1,若不同,则合并。


Code

C++
#include<bits/stdc++.h>
const int N=1e5+5;
int fa[N];
void init(int x)//初始化自己为自己的父亲
{
	for(int i=1;i<=x;i++) fa[i]=i;
	return;
}
int findr(int x)//寻找根
{
	if(fa[x]==x) return x;
	return fa[x]=findr(fa[x]);//类似记忆化
}
void merge(int x,int y)//合并成一个集合
{
	int fx=findr(x);
	int fy=findr(y);
	if(fx==fy) return;
	fa[fy]=fx;
}
int main()
{
	ios::sync_with_stdio(false);//快读
	cin.tie(nullptr);
	cout.tie(nullptr);
	int t;
	cin<<t;
	while(t--)
	{
		int n,m;
		cin>>n>>m;
		memset(fa,0,sizeof fa);//多测要清空
		init(n);
		int ans=m;
		for(int i=1;i<=m;i++)
		{
			int x,y;
			cin>>x>>y;
			if(x==y) ans--;
			else
			{
				if(findr(x)==findr(y)) ans++;//若他们根相同,则需移动步数+1,
				else merge(x,y);//若不同,则合并
			}
		}
		cout<<ans<<endl;
	}
	return;
}

(本题解有3处错误,不要抄题解,会CE哦:))

原文