pSort

这篇博客讨论了一个涉及数组中细胞的游戏。每个细胞有自己的序号和偏好数值,可以与偏好距离内的其他细胞交换数值。给定初始状态和细胞偏好,判断是否能通过无限次移动到达某一特定数组排列。主要算法是使用并查集(union-find)数据结构来追踪细胞的可达性,如果所有元素都能找到相同的根,则状态可达,否则不可达。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

One day n cells of some array decided to play the following game. Initially each cell contains a number which is equal to it's ordinal number (starting from 1 ). Also each cell determined it's favourite number. On it's move i -th cell can exchange it's value with the value of some other j -th cell, if ∣i−j∣=di , where di is a favourite number of i -th cell. Cells make moves in any order, the number of moves is unlimited.

The favourite number of each cell will be given to you. You will also be given a permutation of numbers from 1 to n . You are to determine whether the game could move to this state.

Input

The first line contains positive integer n ( 1<=n<=100 ) — the number of cells in the array. The second line contains n distinct integers from 1 to n — permutation. The last line contains n integers from 1 to n — favourite numbers of the cells.

Output

If the given state is reachable in the described game, output YES, otherwise NO.

思路:

首先初始化获得1~n的元素,并确定各个元素可以同哪一些进行交换。

核心的就是find()函数,相当于是溯源。

只要前后俩个的源头一样就可以互相交换。

#include<iostream>
using namespace std;
const int N=1e4;
int n;
int a[N+5],d[N+5],f[N+5];
void init()
{
	for(int i=1;i<=N;i++)
		f[i]=i;
}
int find(int k)
{
	if(f[k]==k)
		return k;
	return f[k]=find(f[k]);
}
int main()
{
	init();
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i];
	}
	for(int i=1;i<=n;i++)
	{
		cin>>d[i];
		int x,y;
		x=i+d[i];
		y=i-d[i];
		if(x<=n)
		{
			f[find(x)]=find(i);
		}
		if(y>=1)
		{
			f[find(y)]=find(i);
		}
	}
		for(int i=1;i<=n;i++)
		{
			int k=a[i];
			if(find(k)!=find(i))
			{
				cout<<"NO";
				return 0;
			}
		}
	cout<<"YES";
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TherAndI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值