Codeforces Round #692 (Div. 2, based on Technocup 2021 Elimination Round 3) C. Peaceful Rooks (思维,dsu找环)

  • 题意:一个棋盘上有一些"车",现在要让这些"车"跑到左倾斜的对角线上,每次可以移动一个棋子,但是棋盘的任意时刻都不能出现一个"车"能吃另一个"车"的情况.问最少需要移动多少次才能满足条件.("车"的个数小于对角线的格子数).
  • 题解:对于某个棋子的位置((x,y)),我们可以(x->y)来建边,如果棋子已经在对角线上了,那么我们不用移动它们,也就不需要建边,否则一个棋子要么移动(1)次要么移动(2)次,我们发现,对于一个环,其中的某个棋子需要移动两次,剩余的棋子则需移动一次,所以答案就是:总棋子数-对角线上的棋子数+环数.
  • 代码:
#include <bits/stdc++.h>
#define ll long long
#define fi first
#define se second
#define pb push_back
#define me memset
#define rep(a,b,c) for(int a=b;a<=c;++a)
#define per(a,b,c) for(int a=b;a>=c;--a)
const int N = 1e6 + 10;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
using namespace std;
typedef pair<int,int> PII;
typedef pair<ll,ll> PLL;
ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;}
ll lcm(ll a,ll b) {return a/gcd(a,b)*b;}

int t;
int n,m;
int u,v;
int p[N];

int find(int x){
	if(p[x]!=x) p[x]=find(p[x]);
	return p[x];
}

int main() {
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
	cin>>t;
	while(t--){
		cin>>n>>m;

		rep(i,1,n) p[i]=i;

		int cnt=0;

		rep(i,1,m){
			cin>>u>>v;
			if(u==v) {cnt--;continue;}
			int fu=find(u);
			int fv=find(v);
			if(fu==fv) cnt++;
			else p[fu]=fv;
		}

		cout<<m+cnt<<'
';
	}

    return 0;
}
原文地址:https://www.cnblogs.com/lr599909928/p/14169774.html