Increasing Sequences
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 2773 | Accepted: 1039 |
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
#include<iostream> #include <string.h> using namespace std; #define N 100 char a[N]; int dp1[N],dp2[N]; int k; int mystrlen(char a[]){ int i=0; while(a[i]!='\0') i++; return i; } int astrcmp(int s1,int l1,int s2,int l2) { while(a[s1]=='0') s1++; while(a[s2]=='0') s2++; if(((l1-s1)==(l2-s2))&&(l1-s1)>=0&&(l2-s2)>=0){ while(s1<=l1){ if(a[s1]>a[s2]) return 1; else if(a[s1]<a[s2]) return -1; else{ s1++; s2++; } } return 0; } return (l1-s1)>(l2-s2)?1:-1; } void find_incr_seq(int last,int tmp) { int i,j; for(i=tmp-1;i>=0;i--){ for(j=i;j<last;j++){ if(astrcmp(i,j,j+1,dp2[j+1])<0) dp2[i]=j; } } } void mymemset(int dp[],int arr_value,int arr_size) { for(int i=0;i<arr_size;i++) dp[i]=arr_value; } void print_arr(int b,int e){ int i; for(i=b;i<=e;i++){ cout<<a[i]; } } int main(void) { while(cin>>a&&(a[0]!='0'||a[1]!=0)){ int i=0,j,nr; k=0; nr=mystrlen(a); mymemset(dp1,0,N); mymemset(dp2,0,N); for(i=1;i<nr;i++){//find max number in sequence for(j=i;j>=0;j--){ if(astrcmp(j,i,dp1[j-1],j-1)>0){ dp1[i]=j; break; } } } int tmp=dp1[nr-1]; int last=tmp; dp2[last]=nr-1; while(tmp>0&&a[tmp-1]=='0'){// 0 is to considered dp2[tmp-1]=nr-1; tmp--; } if(tmp==0) cout<<a; else{ find_incr_seq(last,tmp);//dp2 i=0;//print result while(true){ print_arr(i,dp2[i]); i=dp2[i]+1; if(i<nr) cout<<','; else break; } } cout<<endl; } }
由于ZOJ的编译器原因,有些函数不得不自己实现。