C. Where is the Pizza?【并查集】

C. Where is the Pizza?
在这里插入图片描述

题意:让你求一个排列数组ci在给定条件下有几种可能:
给你两个1-n的乱序排列a[],b[],再给你一个n个数的d[i]数组,if di==0: 可以选择ai or bi 填充ci,else: ci = di ,让你求c[]有多少可能

思路:其实一开始乱糟糟的没思路,但是模拟一下会发现几个数会组成一个环,而且每一个环的贡献值为2,假设有n个环,那么答案就是2^n;
if ai==bi :贡献值为0 因为只有一种可能
if di != 0: 贡献值为0 因为只有一种可能
而对于一个环:
给大家一组样例:
1 4 2 3
4 3 1 2
通过模拟你会发现只有两种可能:1 4 2 3 and 4 3 2 1
因为一个数确定之后 另一个数的位置也随之确定了,根据环循环一圈这个序列也就确定了,所以我们用并查集维护环的数量求解即可。
挺好一个并查集和思维题的叭(QAQ)

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=2e5+7;
const int mod=1e9+7;
int a[N],b[N],d[N];
int father[N];
int find(int x){
    
    
	if(x==father[x]) return x;
	return father[x]=find(father[x]);
}
void work(){
    
    
	int n;
	cin>>n;
	for(int i=1;i<=n;i++) cin>>a[i];
	for(int i=1;i<=n;i++) cin>>b[i];
	for(int i=1;i<=n;i++) father[i]=i;
	ll ans=1;
	for(int i=1;i<=n;i++){
    
    
		int x;cin>>x;
		if(!x&&a[i]!=b[i]){
    
    
			int dx=find(a[i]);
			int dy=find(b[i]);
			if(dx==dy) ans=ans*2ll%mod;
			else father[dx]=dy;
		}
	}
	cout<<ans%mod<<endl;
}
int main(){
    
    
	int _;
	cin>>_;
	while(_--){
    
    
		work();
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_51461002/article/details/124720883