SPOJ 154 Sweet and Sour Rock

Description

A manufacturer of sweets has started production of a new type of sweet called rock. Rock comes in sticks composed of one-centimetre-long segments, some of which are sweet, and the rest are sour. Before sale, the rock is broken up into smaller pieces by splitting it at the connections of some segments.

Today's children are very particular about what they eat, and they will only buy a piece of rock if it contains more sweet segments than sour ones. Try to determine the total length of rock which can be sold after breaking up the rock in the best possible way.

Input

The input begins with the integer t, the number of test cases. Then t test cases follow.

For each test case, the first line of input contains one integer N - the length of the stick in centimetres (1<=N<=200). The next line is a sequence of N characters '0' or '1', describing the segments of the stick from the left end to the right end ('0' denotes a sour segment, '1' - a sweet one).

Output

For each test case output a line with a single integer: the total length of rock that can be sold after breaking up the rock in the best possible way.

Sample Input

Sample input:
2
15
100110001010001
16
0010111101100000

Sample output:
9
13

题意:有一块n个单位长的糖,有的地方是甜的(1),有的地方是酸的(0)。你可以将整块糖任意切成若干段。小盆友们只会买走甜的长度比酸的长度多的那段糖。问经过切割后,最多可以卖掉多少单位长度的糖。
考察知识:DP
dp(i)表示将前i段糖进行切割后最多能卖掉的数量
状态转移方程:
        考虑在第j段之前切一刀
        dp(i)=max{ dp(i) , dp(j-1) +i–j+1}
        ( 1 <= j <= i 且在[j,i]区间内甜的比酸的多)
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 205;
char str[maxn];
int dp[maxn],sum[maxn][2];

int main(){
    int T,len;
    scanf("%d",&T);
    while(T--){
        scanf("%d %s",&len,str+1);
        sum[0][0] = sum[0][1] = 0;
        for(int i = 1;i <= len;i++){
            sum[i][0] = sum[i-1][0];
            sum[i][1] = sum[i-1][1];
            sum[i][str[i]-'0']++;
        }
        dp[0] = 0;
        for(int i = 1;i <= len;i++){
            dp[i] = dp[i-1];
            for(int j = 1;j <= i;j++){
                int sum0 = sum[i][0]-sum[j-1][0];
                int sum1 = sum[i][1]-sum[j-1][1];
                if(sum1 <= sum0)    continue;
                dp[i] = max(dp[i],dp[j-1]+i-j+1);
            }
        }
        printf("%d\n",dp[len]);
    }
    return 0;
}

由于今天比赛出了一点点意外(啦啦啦,其实是我做了错事~)这道题没来及看,真是的。
不过考完一看,发现是DP,自己看了说不定也做不出来,突然对自己选题的机智又有信心了呢~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值