Codeforces 353C Find Maximum【贪心】

来源:互联网 发布:keygen注册机下载 mac 编辑:程序博客网 时间:2024/06/05 23:59

C. Find Maximum
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

Valera has array a, consisting of n integers a0, a1, ..., an - 1, and functionf(x), taking an integer from 0 to 2n - 1 as its single argument. Valuef(x) is calculated by formula , where value bit(i) equals one if the binary representation of numberx contains a 1 on thei-th position, and zero otherwise.

For example, if n = 4 and x = 11 (11 = 20 + 21 + 23), thenf(x) = a0 + a1 + a3.

Help Valera find the maximum of function f(x) among allx, 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 containsn space-separated integers a0, a1, ..., an - 1(0 ≤ ai ≤ 104) — elements of arraya.

The third line contains a sequence of digits zero and one without spaces s0s1...sn - 1 — the binary representation of numberm. Number m equals.

Output

Print a single integer — the maximum value of function f(x) for all .


题目大意:

给你N个数,以及一个01串s,设定M=Σsi*2^i;

让你找寻max(F[X]),【0<=X<=M】,其中F(x)=∑ai*bit(i),比如F(11)=a0+a1+a3(2^0+2^1+2^3==11);


思路:


1、假设s=00000001.

那么我们贪心的拿取,肯定分成两种情况:

①拿取11111110,F(X)=a0+a1+a2+a3+a4+a5+a6;

②拿取00000001,F(X)=a7;

那么比较两个值的大小,取大的即可。


2、那么接下来假设s=00000101.

那么我们同理贪心的拿取,肯定也分成如下几种情况:

①00000101

②11111001

③11111110

那么比较几个数的大小,取最大的即可。


3、那么思路就很容易确定了:我们从最右边的那个1开始向回扫,遇到一个1,我们可以将其拆分.比如000001,我门就可以拆分成111110的拿取,进行方案的最优统计即可。


Ac代码:


#include<stdio.h>#include<string.h>#include<algorithm>using namespace std;int a[100050];int sum[100050];char b[100050];int main(){    int n;    while(~scanf("%d",&n))    {        for(int i=0;i<n;i++)        {            scanf("%d",&a[i]);        }        int maxpos=-1;        scanf("%s",b);        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(b[i]=='1')maxpos=i;        }        int summ=0,ans=0;        for(int i=maxpos;i>=0;i--)        {            if(b[i]=='1')            {                ans=max(ans,summ+sum[i-1]);                summ+=a[i];            }        }        printf("%d\n",max(ans,summ));    }}



0 0