Increasing Sequences
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 2903 | Accepted: 1092 |
Description
Given a string of digits, insert commas to create a sequence of strictly increasing numbers so as to minimize the magnitude of the last number. For this problem, leading zeros are allowed in front of a number.
Input
Input will consist of multiple test cases. Each case will consist of one line, containing a string of digits of maximum length 80. A line consisting of a single 0 terminates input.
Output
For each instance, output the comma separated strictly increasing sequence, with no spaces between commas or numbers. If there are several such sequences, pick the one which has the largest first value;if there's a tie, the largest second number, etc.
Sample Input
3456 3546 3526 0001 100000101 0
Sample Output
3,4,5,6 35,46 3,5,26 0001 100,000101
题意:添加逗号使其变成一个严格递增的序列,要求最后一个数最小,如果有多解,第一个数取大的,第一个数相同时取第二个数大的,依次类推。
思路:首先dp[i]表示i到dp[i]可能的最小的数,这样可以得到最小的最后一个数,然后再往前递推,尽量得到大的数。
写得不够优雅,但是懒得改了…………
AC代码如下:
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
using namespace std;
char s[100];
int num[100][100],value[100],dp[110];
int judge(int a,int b,int c,int d)
{ int i,j,k;
while(s[a]=='0' && a<b)
a++;
while(s[c]=='0' && c<d)
c++;
if(b-a>d-c)
return 2;
if(b-a<d-c)
return 0;
for(i=0;i<=b-a;i++)
{ if(s[a+i]>s[c+i])
return 2;
if(s[a+i]<s[c+i])
return 0;
}
return 1;
}
int main()
{ int n,m,i,j,k,pos,ret;
while(~scanf("%s",s+1))
{ n=strlen(s+1);
if(n==1 && s[1]=='0')
break;
for(i=1;i<=n;i++)
dp[i]=1;
for(i=2;i<=n;i++)
for(j=1;j<=i;j++)
if(judge(j,i,dp[j-1],j-1)==2)
dp[i]=j;
k=dp[n];
dp[k]=n;
for(j=k-1;j>=1;j--)
{ for(i=j;i>=1;i--)
{ if(s[i]=='0')
{ dp[i]=dp[i+1];
continue;
}
if(judge(i,j,j+1,dp[j+1])==0)
dp[i]=max(dp[i],j);
}
}
pos=1;ret=dp[1];
while(true)
{ for(;pos<=ret;pos++)
printf("%c",s[pos]);
if(pos==n+1)
break;
printf(",");
ret=dp[pos];
}
printf("\n");
}
}