前排感谢 @Leonard.7 大佬给的思路qwq
没有大佬的帮助我这个菜批A不掉这道题qwq
原题
You are given an array [a1,a2,…,an] such that 1≤ai≤109. Let S be the sum of all elements of the array a.
Let’s call an array b of n integers beautiful if:
1≤bi≤109 for each i from 1 to n;
for every pair of adjacent integers from the array (bi,bi+1), either bi divides bi+1, or bi+1 divides bi (or both);
2∑i=1n|ai−bi|≤S.
Your task is to find any beautiful array. It can be shown that at least one beautiful array always exists.
Input
The first line contains one integer t (1≤t≤1000) — the number of test cases.
Each test case consists of two lines. The first line contains one integer n (2≤n≤50).
The second line contains n integers a1,a2,…,an (1≤ai≤109).
Output
For each test case, print the beautiful array b1,b2,…,bn (1≤bi≤109) on a separate line. It can be shown that at least one beautiful array exists under these circumstances. If there are multiple answers, print any of them.
简单的解释
给一个数组a,其数组各个数的和为S,让你求一个数组b符合以下条件:
- b[i] ∈ [1,1e9]
- 2*∑|a[i]-b[i]| <= S
- b[i]可以被b[i+1]整除或被整除
这里是一个基本上压着最大值的解法。
以数组1,3,2,5,4举例,首先把这个数组以单双数分开,即
1 ,2, 4 和 3,5
被分开的这两个数组的其中一个的和必然大于S/2。
在这个例子中也就是1,2,4。
这样看来如果我们想要求出数组b,即数组b中的数为1,x,2,x,4。
显而易见的是x=1。此题得证。
以下是写的非常不简便的代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
const int N = 100;
using namespace std;
int main(){
int n;
cin >> n;
for(int i = 0;i < n;i++){
int x,a[N],b[N];
long long sum = 0,tot = 0;
cin >> x;
for(int j = 0;j < x;j++){
cin >> a[j];
tot+= a[j]; //求S
if(j % 2==0) b[j] = 1;
else b[j] = a[j];
sum+=abs(a[j]-b[j]); //计算∑|a[i]-b[i]|
}
if(2*sum < tot) //两种情况进行判断,这里又又双写麻烦了
for(int j = 0;j < x;j++)cout << b[j] << " ";
else{ //第二种情况
for(int j = 0;j < x;j++){
if(j%2!=0) b[j] = 1;
else b[j] = a[j];
}
for(int j = 0;j < x;j++)cout << b[j] << " ";
}
cout << endl;
}
return 0;
}