鼠人今天写了每日一题,有个数学题蛮有意思的,我们来看看吧(顺便水一篇博客)
一、题目
CF-1463
B. Find The Array
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.
Example
input
4
5
1 2 3 4 5
2
4 6
2
1 1000000000
6
3 4 8 1 2 3
output
3 3 3 3 3
3 6
1 1000000000
4 4 8 1 3 3
不想读题看这里
知道你们不想看英文(我也不喜欢),我把题干大致解说一下。
现在给你一个数组a,里面有n个元素,元素之和是S,请你构造一个数组长度同为n的b数组,满足以下条件:
1.b数组内任意一个元素满足可以被数组两边的元素整除,或者整除数组两边的元素
2.从1遍历到n,满足|a[i]-b[i]|<=S/2(也就是b数组内的元素大概要在a附近,或者说,方差要小)
二、想法
我们看条件一,要满足“b数组内任意一个元素满足可以被数组两边的元素整除”这个条件,我们很容易想到1是万能的,所以我们只需要把a数组某些元素改成1就可以了
条件二要满足a,b方差够小,那其实我们只用把a数组内奇数位,偶数位分别相加对比,如果偶数位和大,就把奇数位改成1,如果奇数大则相反
来实现吧!
三、AC代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int main()
{
int a[100];
int t,n;
//注意,由于a元素属于int所以sum要设置为long long
ll sum1,sum2;
cin >> t;
while(t--)
{
memset(a,0,sizeof a);
sum1 = sum2 = 0;
cin >> n;
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
if(i&1)sum1 += a[i];
else sum2 += a[i];
}
//偶数和大于奇数和的情况
if(sum1<sum2)
for(int i=1;i<=n;i+=2)a[i] = 1;
else
for(int i=2;i<=n;i+=2)a[i] = 1;
for(int i=1;i<=n;i++){
if(i!=n)printf("%d ",a[i]);
else printf("%d\n",a[i]);
}
}
return 0;
}
四、另一种想法
用2的幂次去构造
#include<bits/stdc++.h>
using namespace std;
#define maxn 100010
#define PI acos(-1)
#define INF 0x3f3f3f
#define ll long long
ll f(ll x)
{
ll h = 1;
while(h < x)
{
h *= 2;
}
if (h == 1) return 1;
return h/2;
}
ll a[100];
ll b[100];
int main()
{
int t;
cin >> t;
while(t--)
{
int n;
scanf("%d",&n);
ll sum1 = 0, sum2 = 0;
for (int i = 1; i <= n; i++)
{
scanf("%lld",&a[i]);
b[i] = f(a[i]);
}
for (int i = 1; i <= n; i++)
{
printf("%lld ", b[i]);
}
printf("\n");
}
return 0;
}
总结
这里总结一下解构造题的方法:首先,看清条件,确保不要漏掉什么重点;接着就是找规律,尝试打表或者寻找样例特点,做出一些总结;然后就是要注意一些小细节,比如上题的sum要定义成long long。