Algorithm


Problem link- https://www.spoj.com/problems/ROCK/

ROCK - Sweet and Sour Rock

 

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.

Example

Sample input:
2
15
100110001010001
16
0010111101100000

Sample output:
9
13

 

Code Examples

#1 Code Example with C++ Programming

Code - C++ Programming

#include <iostream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <sstream>
#include <map>
#include <list>

using namespace std;
int dp[201][201];
int freq[201][201];
int n;

int calculate(int i,int j){
	if(i==j)return dp[i][i];
	if(dp[i][j]!=-1)return dp[i][j];
	for(int k=i;k<j;k++){
		dp[i][k]=calculate(i,k);
		dp[k+1][j]=calculate(k+1,j);
		if(freq[i][k]+freq[k+1][j]>((j-i+1)/2))
			dp[i][j]=(j-i+1);
		else
			dp[i][j]=max(dp[i][j],dp[i][k]+dp[k+1][j]);
		/*else
			dp[i][j]=max(dp[i][j],freq[i][k]+freq[k+1][j]);*/
	}
	return dp[i][j];
}

int main(){
	int t;
	scanf("%d",&t);
	while(t--){
		scanf("%d",&n);
		char s[201];
		scanf("%s",s);
		memset(dp,-1,sizeof(dp[0][0])*201*201);
		for(int i=0;i<n;i++){
			freq[i][i]=s[i]-'0';
			dp[i][i]=freq[i][i];
		}
		for(int i=0;i<n;i++){
			for(int j=i+1;j<n;j++){
				freq[i][j]=freq[i][j-1]+(s[j]-'0');
			}
		}
		cout<<calculate(0,n-1)<<endl;
		/*for(int i=0;i<n;i++){
			for(int j=0;j<n;j++){
				cout<<dp[i][j]<<" ";
			}
			cout<<endl;
		}*/
	}
	return 0;
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
2
15
100110001010001
16
0010111101100000

Output

x
+
cmd
9
13
Advertisements

Demonstration


SPOJ Solution-ROCK Sweet and Sour Rock-Solution in C, C++, Java, Python ,SPOJ Solution

Previous
SPOJ Solution - Test Life, the Universe, and Everything - Solution in C, C++, Java, Python