练习codeforces 1941B. Rudolf and 121
题目如下
B. Rudolf and 121
time limit per test2 seconds
memory limit per test256 megabytes
Rudolf has an array 𝑎 of 𝑛 integers, the elements are numbered from 1 to 𝑛.
In one operation, he can choose an index 𝑖 (2≤𝑖≤𝑛−1) and assign:
𝑎𝑖−1=𝑎𝑖−1−1
𝑎𝑖=𝑎𝑖−2
𝑎𝑖+1=𝑎𝑖+1−1
Rudolf can apply this operation any number of times. Any index 𝑖 can be used zero or more times.
Can he make all the elements of the array equal to zero using this operation?
Input
The first line of the input contains a single integer 𝑡 (1≤𝑡≤104) — the number of test cases in the test.
The first line of each case contains a single integer 𝑛 (3≤𝑛≤2⋅105) — the number of elements in the array.
The second line of each case contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (0≤𝑎𝑗≤109) — the elements of the array.
It is guaranteed that the sum of the values of 𝑛 over all test cases does not exceed 2⋅105.
Output
For each test case, output "YES" if it is possible to make all the elements of the array zero using the described operations. Otherwise, output "NO".
You can output each letter in any case (lowercase or uppercase). For example, the strings "yEs", "yes", "Yes", and "YES" will be accepted as a positive answer.
题目大意
是否能通过多次
𝑎𝑖−1=𝑎𝑖−1−1
𝑎𝑖=𝑎𝑖−2
𝑎𝑖+1=𝑎𝑖+1−1的操作使得数组中所有元素都为0
题目分析
从左到右尝试将每个元素及其前后进行尝试,注意索引是从0开始,操作也对应
点击查看代码
for(int i = 1; i <= n - 3; i++){
if(a[i] < 0){ //判断失败
possible = 0;
break;
}
int k = a[i];
a[i] -= k; // a[i] = 0
a[i+1] -= 2 * k; //模拟k次操作
a[i+2] -= k;
if(a[i+1] < 0 || a[i+2] < 0){
possible = 0;
break;
}
}
因为操作范围的限制,最后还要检查数组最后两个元素是否已经清为 0
点击查看代码
for(int i = n - 2; i < n; i++){
if(a[i] != 0){
possible = 0;
break;
}
}
完整代码
点击查看代码
#include <stdio.h>
int main(){
int t;
scanf("%d", &t);
while (t--){
int n;
scanf("%d", &n);
int a[200005];
for (int i = 0; i < n; i++){
scanf("%d", &a[i]);
}
int possible = 1;
for(int i = 0; i <= n - 3; i++){
if(a[i] < 0){ //判断失败
possible = 0;
break;
}
int k = a[i];
a[i] -= k; //模拟k次
a[i+1] -= 2 * k;
a[i+2] -= k;
if(a[i+1] < 0 || a[i+2] < 0){
possible = 0;
break;
}
}
for(int i = n - 2; i < n; i++){
if(a[i] != 0){
possible = 0;
break;
}
}
if (possible)
printf("YES\n");
else
printf("NO\n");
}
return 0;
}

浙公网安备 33010602011771号