Find Maximum (二进制)
CodeForces - 353C
Find Maximum
Valera has array a, consisting of n integers a0, a1, …, an - 1, and function f(x), taking an integer from 0 to 2n - 1 as its single argument. Value f(x) is calculated by formula , where value bit(i) equals one if the binary representation of number x contains a 1 on the i-th position, and zero otherwise.
For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), then f(x) = a0 + a1 + a3.
Help Valera find the maximum of function f(x) among all x, for which an inequality holds: 0 ≤ x ≤ m.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of array elements. The next line contains n space-separated integers a0, a1, …, an - 1 (0 ≤ ai ≤ 104) — elements of array a.
The third line contains a sequence of digits zero and one without spaces s0s1… sn - 1 — the binary representation of number m. Number m equals .
Output
Print a single integer — the maximum value of function f(x) for all .
Examples
Input
2
3 8
10
Output
3
Input
5
17 0 10 2 1
11010
Output
27
Note
In the first test case m = 20 = 1, f(0) = 0, f(1) = a0 = 3.
In the second sample m = 20 + 21 + 23 = 11, the maximum value of function equals f(5) = a0 + a2 = 17 + 10 = 27.
题意:给一个二进制数m,在0<=x<=m中找到最佳的x,使得x对应的二进制数为1的i求和的sum最大。
想法:如果高位为1,那么低位可以全部换成1。如000001,就可以去和111110比较sum大小,001001与110001比较。第i个为1,前i-1变为1,i+1后不变,这样处理到最后一个为1的数位时答案就出来了。
#include<bits/stdc++.h>
using namespace std;
#define M 100500
int a[M];
char zo[M];//储存01串
int sum[M];//用前缀和,不然TLE
int main()
{
int n,ans=0;
int maxpos=0;
scanf("%d",&n);
for (int i=0;i<n;i++)
scanf("%d",&a[i]);
scanf("%s",zo);
sum[0]=a[0];//初始化
for (int i=1;i<n;i++)
sum[i]=sum[i-1]+a[i];
for(int i=0;i<n;i++)
{
if(zo[i]=='1')
{
ans+=a[i];
maxpos=i;
}
}//遍历找到最高位的1。ans先置为01串本身对应的sum,这样避免000001这样的数据出问题
int summ=0;//遇到1时后面的和。
for (int j=maxpos;j>0;j--)
{
if (zo[j]=='1')
{
ans=max(ans,summ+sum[j-1]);//比较
summ+=a[j];//1用过后加到summ去
}
}
printf("%d\n",ans);
system ("pause");//不知道为什么,加这个会Runtimeerror
return 0;
}
本题有简单动态规划的感觉,也可以用dp做。
设g(i)是长度为i时的最优解,那么每次遇到1时
g(i)=max(sum(i-1),g(i-1)+a[i])
当不为1时,g(i)=g(i-1)
over.
本文介绍了一道CodeForces上的题目,要求在0到给定二进制数m之间找到一个数x,使得x的二进制表示中1的位置所对应的数组元素之和最大。通过动态规划的方法解决了这一问题,并给出了详细的实现思路和代码。
1519

被折叠的 条评论
为什么被折叠?



