您的位置:首页 > 运维架构

【动态规划】 TopCoder SRM 555 CuttingBitString

2012-10-15 22:35 253 查看
大致意思就是把一个01串切分成一系列是5的幂次方的子串,题意叙述简洁,是一道很好的动态规划题目。

We are in a distant future. After the downfall of mankind, the Earth is now ruled by fairies. The "Turing game Online" website is hot among fairies right now. On this website, everyone can play the programming puzzle "Turing game".

Fairies love powers of 5, that is, the numbers 1, 5, 25, 125, 625, and so on. In the Turing game, the player is given a string of bits (zeros and ones). The ideal situation is when the string is represents a power of 5 in binary, with no leading zeros. If
that is not the case, the fairy player tries to cut the given string into pieces, each piece being a binary representation of a power of 5, with no leading zeros. Of course, it may be the case that even this is impossible. In that case, the fairy player becomes
depressed, and bad things happen when a fairy gets depressed. You, as one of the surviving humans, are in charge of checking the bit strings to prevent the bad things from happening.

You are given a String S that consists of characters '0' and '1' only. S represents the string given to a player of the Turing game. Return the smallest positive integer K such that it is possible to cut S into
K pieces, each of them being a power of 5. If there is no such K, return -1 instead.

我的源代码:

#include<string>
#include<vector>
#include<algorithm>
#define MAXIMUM 99999

using namespace std;

class CuttingBitString{
public:
//get min using dynamic programming method
int getmin(string s){
int len=s.size();
int goal[60];
for(int i=0;i<len;i++){
goal[i]=MAXIMUM;
}
for(int i=0;i<len;i++){
//additional test
if(isFit(s,0,i)==true){
// 1 will be the minimum number
goal[i]=1;
continue;
}
for(int j=0;j<i;j++){
//right substring is not power of 5
if(isFit(s,j+1,i)==false)
continue;
///front substring is not power of 5
if(goal[j]==MAXIMUM)
continue;
goal[i]=min(goal[i],goal[j]+1);
}
}//end external for loop
//there is no solution
if(goal[len-1]==MAXIMUM)
return -1;
return goal[len-1];
}

//return if this substring is the power of 5
bool isFit(string s,int begin,int end){
if(begin>end)
return false;
//long long data type is enough for this problem
long long counter=0;
for(int i=begin;i<=end;i++){
if(s[i]=='0')
counter=counter<<1;
else if(s[i]=='1')
counter=(counter<<1)+1;
}
if(counter==0)
return false;
//test whether it is the power of 5
while(counter%5==0){
counter=counter/5;
}
//the power of five will lead to 1 in the end
if(counter==1)
return true;
return false;
}
};


离线测试了一下,应该是对的,具体大家如果感兴趣可以到TopCoder的网站上去看,非常详细(这是我觉得TopCoder与传统OJ相比的很大优势了……)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: