题目 | ± Increasing Sequence
AtCoder Regular Contest 153
C - ± Increasing Sequence
https://atcoder.jp/contests/arc153/tasks/arc153_c
Problem Statement
You are given a sequence of length
Determine whether there is an integer sequence
for every ( ). is strictly increasing. That is, . .
Constraints
Input
The input is given from Standard Input in the following format:
Output
If there is an integer sequence Yes
; otherwise, print No
. In case of Yes
, print the elements of such an integer sequence
If multiple integer sequences satisfy the conditions, you may print any of them.
Sample Input 1
5
-1 1 -1 -1 1
Sample Output 1
Yes
-3 -1 4 5 7
For this output, we have
Sample Input 2
1
-1
Sample Output 2
Yes
0
Sample Input 3
2
1 -1
Sample Output 3
No
题解
这道题很明显是一道构造题,构造题解法往往有挺多的,不过只要能把答案凑出来就行。我的构造思路是:
- 直接用
作为初始解,算出 - 如果
那么想办法让 减小为 - 如果
那么想办法让 增大为
于是,解题核心就在于如何调整
由于这两种情况完全对称,我们只以
对于我们的初始解,有两种操作能保证操作后仍然符合严格单调递增:
- 将第
位同时增大 ( ) - 将第
位同时减小 ( )
那么我们就用这两种操作来控制
对于第一种操作,若第
对于第二种操作,若第
这样,只要我们能找到满足两种操作其中一种的
如果我们两种操作都找不到满足条件的 No
即可。
代码
#include <bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
signed main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int N;
cin >> N;
vector<int> A(N + 1);
for (int i = 1; i <= N; i++)
cin >> A[i];
int sum = 0;
for (int i = 1; i <= N; i++)
sum += A[i] * i;
if (sum > 0)
{
int cnt_posi = 0, cnt_nega = 0, pos = 0;
for (int i = N; i >= 1; i--)
{
if (A[i] == 1)
cnt_posi++;
else
cnt_nega++;
if (cnt_nega > cnt_posi)
{
pos = i;
break;
}
}
if (pos)
{
cout << "Yes" << endl;
for (int i = 1; i < pos; i++)
cout << i << ' ';
for (int i = pos; i <= N; i++)
cout << i + sum << ' ';
cout << endl;
return 0;
}
cnt_posi = 0, cnt_nega = 0;
for (int i = 1; i <= N; i++)
{
if (A[i] == 1)
cnt_posi++;
else
cnt_nega++;
if (cnt_posi > cnt_nega)
{
pos = i;
break;
}
}
if (pos)
{
cout << "Yes" << endl;
for (int i = 1; i <= pos; i++)
cout << i - sum << ' ';
for (int i = pos + 1; i <= N; i++)
cout << i << ' ';
cout << endl;
return 0;
}
}
else
{
int cnt_posi = 0, cnt_nega = 0, pos = 0;
for (int i = N; i >= 1; i--)
{
if (A[i] == 1)
cnt_posi++;
else
cnt_nega++;
if (cnt_nega < cnt_posi)
{
pos = i;
break;
}
}
if (pos)
{
cout << "Yes" << endl;
for (int i = 1; i < pos; i++)
cout << i << ' ';
for (int i = pos; i <= N; i++)
cout << i - sum << ' ';
cout << endl;
return 0;
}
cnt_posi = 0, cnt_nega = 0;
for (int i = 1; i <= N; i++)
{
if (A[i] == 1)
cnt_posi++;
else
cnt_nega++;
if (cnt_posi < cnt_nega)
{
pos = i;
break;
}
}
if (pos)
{
cout << "Yes" << endl;
for (int i = 1; i <= pos; i++)
cout << i + sum << ' ';
for (int i = pos + 1; i <= N; i++)
cout << i << ' ';
cout << endl;
return 0;
}
}
cout << "No" << endl;
return 0;
}
本文采用 CC BY-SA 4.0 许可,本文 Markdown 源码:Haotian-BiJi