Problem F: Best string Orz~
Time Limit: 3 Sec Memory Limit: 64 MBSubmit: 1 Solved: 1
[ Submit][ Status][ Web Board]
Description
If a string S is made up by n1 'O',n2 'r', n3 'z' and n4 '~',(n1>=n2>=n3>=n4),and for all of its prefix substring C,if in C the number of 'O' is larger or equal than the number of 'r',the number of 'r' is larger or equal than the number of 'z' and the number of 'z' is larger or equal than the number of '~',then we call it best string.
Now give you the n1,n2,n3,n4,I wonder how many best strings are there with only n1 'O',n2 'r',n3 'z',n4 '~';
Input
There are more than one input.
Each input is four number n1,n2,n3,n4,end by four zeros,which shouldn't be processed.(0<=n1,n2,n3,n4<10)
Output
For each input,print the number of best string.
Sample Input
1 1 1 14 3 2 11 2 3 00 0 0 0
Sample Output
17680
题目大意:一个字符串有四种符号组成,每种n1,n2,n3,n4个,然后问能排成多少种符合要求的: c1>=c2>=c3>=c4 作为前缀……
此题的思路是四个for嵌套,n1在最里面,然后取剩下的数排列下就好;
还未实现不知对错!
下面是另一种实现方式,暂且保存下来再说吧!
山科的测试终于开放了,下面的代码也终于被证实是超时的,而且超的不是一点半点; 就算是本地测试好久也没测出来!!! 要是早点自己测测的话就不会罚时了
而且int型的是存不下的! 后来还是在宏宝大神的指导下才想明白的!
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
int n[5];
int ans;
int c[5];
bool isok()
{
if(c[1]>=c[2]&&c[2]>=c[3]&&c[3]>=c[4])
{
return true;
}
else return false;
}
void f()
{
// cout<<c[1]<<" "<<c[2]<<" "<<c[3]<<" "<<c[4]<<endl;
if(c[1]==n[1]&&c[2]==n[2]&&c[3]==n[3]&&c[4]==n[4])
{
if(isok())ans++;
return;
}
for(int i=1; i<=4; ++i)
{
if(c[i]+1<=n[i])
{///又增加才有可能下一步递归,否则死循环
c[i]++;
if(isok()){ f(); c[i]--;}
else if(!isok())c[i]--;
}
}
}
int main()
{
///1014
while(cin>>n[1]>>n[2]>>n[3]>>n[4])
{
if(n[1]+n[2]+n[3]+n[4]==0)break;
memset(c,0,sizeof(c));
ans=0;
if(!(n[1]>=n[2]&&n[2]>=n[3]&&n[3]>=n[4]))
{
cout<<0<<endl;
continue;
}
else {f();cout<<ans<<endl;}
}
return 0;
}
附上正确的代码!
话说这个题让我想明白了好多! 醍醐灌顶啊!!! 对dp的理解又增加了一层!!
狗日的数据量,原来不是卡时间,而是卡类型啊!!!
long long
#include<stdio.h>
#include<iostream>
#include<cstring>
using namespace std;
#define FOR(a,b) for(int )
bool isok(int a,int b,int c,int d)
{
if(a<0||b<0||c<0||d<0)return false;
if(a<=b&&b<=c&&c<=d)return true;
return false;
}
int main()
{
long long dp[11][11][11][11];
int n1,n2,n3,n4;
while(1)
{
cin>>n1>>n2>>n3>>n4;
if(n1+n2+n3+n4==0)break;
memset(dp,0,sizeof(dp));
dp[0][0][0][1]=1;///这里
// dp[1][1][0][0]=1;
// dp[1][1][1][0]=1;
// dp[1][1][1][1]=1;
for(int i4=0;i4<=n4;++i4)
{
for(int i3=0;i3<=n3;++i3)
for(int i2=0;i2<=n2;++i2)
for(int i1=0;i1<=n1;++i1)
if(isok(i4,i3,i2,i1))
{
if(isok(i4,i3,i2,i1-1))dp[i4][i3][i2][i1]+=dp[i4][i3][i2][i1-1];
if(isok(i4,i3,i2-1,i1))dp[i4][i3][i2][i1]+=dp[i4][i3][i2-1][i1];
if(isok(i4,i3-1,i2,i1))dp[i4][i3][i2][i1]+=dp[i4][i3-1][i2][i1];
if(isok(i4-1,i3,i2,i1))dp[i4][i3][i2][i1]+=dp[i4-1][i3][i2][i1];
}
else dp[i4][i3][i2][i1]=0;
}
cout<<dp[n4][n3][n2][n1]<<endl;
}
return 0;
}