先说一下题意,给你一个数字n,然后给你n个数,和一个n位的二进制的数。求从0到这个二进制数表示的十位数m之间,所有的十进制数变成的二进制数与数组中的元素进行乘积所组成的数字和的最大值。可能说的有点拗口。。。举例说明吧:5 17 0 10 2 1 11010 n为5,数组中的元素依次是17 0 10 2 1 ,二进制数是11010就是十进制中的11;从十进制0到11中找到一个数字,使得p[i]*i(位上的数字(0,1))得到的和最大。这个题找到的是5,10100,所以是1*17+0*0+1*10+0*2+0*1 = 27,最大。
解题思路:
先是预处理所有的数组,求他们的 前缀和,然后找到第一个出现1的位置,判断将其变成0之后得到的和,与当前的和进行比较,如果大就更新。
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 xcontains 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.
The first line contains integer n (1 ≤ n ≤ 105) — the number of array elements. The next line contains n space-separated integersa0, 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. Numberm equals .
Print a single integer — the maximum value of function f(x) for all .
2 3 8 10
3
5 17 0 10 2 1 11010
27
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.
#include <stdio.h>
#include <string.h>
#include <cmath>
#include <iostream>
#include <map>
using namespace std;
int sum[100100], p[100100];
char str[100100];
int main()
{
int ans = 0, i, n;
int t = 0, f = 0;
scanf("%d",&n);
for(i = 0; i < n; i++)
scanf("%d",&p[i]);
scanf("%s",str);
sum[0] = p[0];
for(i = 1; i < n; i++)
sum[i] = sum[i-1]+p[i];
for(i = 0; i < n; i++)
{
if(str[i] == '1')
{
t += p[i];
f = i;
}
}
ans = t;
t = 0;
for(i = f; i > 0; i--)
{
if(str[i] == '1')
{
ans = max(ans, sum[i-1]+t);
t += p[i];
}
}
printf("%d\n",ans);
return 0;
}