KSzsh

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

Ian and Array Sorting

题目链接

题目描述:

To thank Ian, Mary gifted an array a of length n to Ian. To make himself look smart, he wants to make the array in non-decreasing order by doing the following finitely many times: he chooses two adjacent elements ai and ai+1 (1in1), and increases both of them by 1 or decreases both of them by 1. Note that, the elements of the array can become negative.

As a smart person, you notice that, there are some arrays such that Ian cannot make it become non-decreasing order! Therefore, you decide to write a program to determine if it is possible to make the array in non-decreasing order.

输入描述:

The first line contains a single integer t(1t104) — the number of test cases. The description of test cases follows.

The first line of each test case consists of a single integer n(2n3105) — the number of elements in the array.

The second line of each test case contains n integers a1,a2,,an(1ai109) — the elements of the array a.

It is guaranteed that the sum of nover all test cases does not exceed 3105.

输出描述:

For each test case, output "YES" if there exists a sequence of operations which make the array non-decreasing, else output "NO".

You may print each letter in any case (for example, "YES", "Yes", "yes", "yEs" will all be recognized as positive answer).

样例:

input:

5
3
1 3 2
2
2 1
4
1 3 5 7
4
2 1 4 3
5
5 4 3 2 1

output:

YES
NO
YES
NO
YES

AC代码:

思路:

这个题直接写没有思路,但是可以转换成a2a1,a3a2...anan1

设这个数组为b1,b2,...bn1

a1,a2...an是一个非递减序列当且仅当b数组为非负数

最后可以看到有两种改变的情况

  • i1~n3时,bi 加或减 1,则 bi+2 减或加1

  • 单独改变b2bn2且不影响其他数

当在n为奇数时,n2为奇数。所以对于bn2我们可以给它加上足够大的数

那么i为奇数时,我们可以任意改变其他i为奇数的b的值使得它们为非负数

i为偶数时同理,给b2加上足够大的数,使得其他i为偶数的b的值为非负数

n为偶数时,n2为偶数,我们给b2bn2加上足够大的数,此时只能保证i为偶数时b的值都为非负数

i为奇数的b的值,我们可以随意分配,但是b的值的总和都是不变的

所以此时只要将i为奇数时的b的总和加起来,其值大于等于0则代表可以保证b的值为非负数

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
void solve()
{
int n;
cin >> n;
vector<int> a(n + 1);
for(int i = 1; i <= n; i ++)
cin >> a[i];
if(n % 2 == 1)
{
cout << "YES\n";
return;
}
LL sum = 0;
for(int i = 2; i <= n; i += 2)
sum += a[i] - a[i - 1];
if(sum >= 0)
{
cout << "YES\n";
return;
}
cout << "NO\n";
}
int main()
{
ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
int T;
cin >> T;
while(T --)
solve();
return 0;
}

posted on   KSzh  阅读(68)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示