WeirdSort

You are given an array aa of length nn.

You are also given a set of distinct positions p_1, p_2, \dots, p_mp1​,p2​,…,pm​, where 1 \le p_i < n1≤pi​<n. The position p_ipi​ means that you can swap elements a[p_i]a[pi​] and a[p_i + 1]a[pi​+1]. You can apply this operation any number of times for each of the given positions.

Your task is to determine if it is possible to sort the initial array in non-decreasing order (a_1 \le a_2 \le \dots \le a_na1​≤a2​≤⋯≤an​) using only allowed swaps.

For example, if a = [3, 2, 1]a=[3,2,1] and p = [1, 2]p=[1,2], then we can first swap elements a[2]a[2] and a[3]a[3] (because position 22 is contained in the given set pp). We get the array a = [3, 1, 2]a=[3,1,2]. Then we swap a[1]a[1] and a[2]a[2] (position 11 is also contained in pp). We get the array a = [1, 3, 2]a=[1,3,2]. Finally, we swap a[2]a[2] and a[3]a[3] again and get the array a = [1, 2, 3]a=[1,2,3], sorted in non-decreasing order.

You can see that if a = [4, 1, 2, 3]a=[4,1,2,3] and p = [3, 2]p=[3,2] then you cannot sort the array.

You have to answer tt independent test cases.

 题意:给出打乱顺序的1~n的数,和m个数代表位置(假设给的x那么就可以交换x和x+1的数),最终使其变为从小到大的顺序。

思路:首先找到两个顺序不一样的数,如果在这之间存在不能交换的位置,那么就一定不能完成。

反之则可以完成。

#include<iostream>
using namespace std;
const int N = 110;   
int a[N]; 
int b[N];  //用来记录位置是否可以交换。
int flag;  // 记录是否可以完成交换。
int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n, m,x;
		memset(b, 0, sizeof(b));
		cin >> n >> m;
		for (int i = 1; i <= n; ++i)  cin >> a[i];
		while (m--)
		{
			cin >> x;
			b[x] = 1;         //记录哪个位置可以交换。
		}

		for (int i = 1; i <= n; ++i)
		{
			flag = 0;
			for (int j = i + 1; j <= n; ++j)
			{
				if (a[i] > a[j])
				{
					for (int k = i; k < j; ++k)
					{
						if (!b[k])
						{
							flag = 1;
							break;
						}
					}
					if (flag) break;
				}
				if (flag) break;
			}
			if (flag) break;
		}
		if (flag)  cout << "NO" << endl;
		else cout << "YES" << endl;
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值