【数组排序】B. Hemose Shopping

题目来源

Problem - A - CodeforcesCodeforces. Programming competitions and contests, programming communityhttps://codeforces.com/contest/1592/problem/A

题干

解释

当n>=2*x的时候,任何棋子(将数想象成棋子)都可以到达任何一个点

这个可以用数学归纳法证明 省略

当n<2*x的时候,此时除了从头开始数前n-x个棋子和从尾开始数后n-x个棋子可以随意移动位置之外,其他中间的棋子都不可以改变位置,因此排序前后这些棋子的位置都是一样的

我们可以用sort函数将这些棋子都排序好,然后再比较是否保持原位,如果不是,则输出NO

代码段

void solve()//hemose shopping
{
	int n, x;
	cin >> n >> x;
	vector<int>a(n);
	vector<int>b(n);
	for (auto& x : a)cin >> x;
	for (int i = 0; i < n; i++)b[i] = a[i];
	if (n >= 2*x)
	{
		cout << "YES" << endl;
		return;
	}
	else
	{
		sort(b.begin(), b.begin() + n);
		for (int i = n - x; i < x; i++)
		{
			if (b[i] != a[i])
			{
				cout << "NO" << endl;
				return;
			}
		}
		cout << "YES" << endl;
		return;
	}
}

おすすめ

転載: blog.csdn.net/nathanqian123/article/details/121282331