題目:
鍵盤輸入一個高精度的正整數n(<=240位),
去掉任意s個數字后剩下的數字按原左右次序將組成一個新的正整數。
編程對給定的n和s,尋找一種方案,使得剩下的數最小。
Simple Input
178543
4
Simple Output
13
思路:
每一步總是選擇一個使剩下的數最小的數字刪除,即按高位到低位的順序搜索,若各位數字遞增,則刪除最后一個數字;否則刪除第一個遞減區間的首字符,這樣刪一位便形成了一個新的數字串。然后回到串首,按上述規則再刪除下一個數字
參考借鑒代碼1如下:
1 #include<iostream> 2 #include<string> 3 using namespace std; 4 int main() 5 { 6 string n; 7 int s,i,x,l,m; 8 while(cin>>n>>s) 9 { 10 i=-1,m=0,x=0; 11 l=n.length(); 12 while(x<s&&m==0) 13 { 14 i++; 15 if(n[i]>n[i+1])//出現遞減,刪除遞減的首數字 16 { 17 n=n.erase(i,1); 18 x++;// x統計刪除數字的個數 19 i=-1;//從頭開始查遞減區間 20 } 21 if(i==l-x-2&&x<s) 22 m=1;//已經無遞減區間,m=1脫離循環 23 } 24 cout<<n.substr(0,l-s+x)<<endl;//只打印剩下的左邊l-(s-x)個數字 25 } 26 return 0; 27 }
參考借鑒代碼2如下:
1 #include<stdio.h> 2 int main() 3 { 4 int i,n,num,tail,head; 5 char q[100],s[100]; 6 while(~scanf("%s%d",s,&n)){ 7 tail=head=num=i=0; 8 q[tail++]=s[i++]; 9 while(s[i]){ 10 if(s[i]>q[tail-1]||num>=n) 11 q[tail++]=s[i++]; 12 else{ 13 if(head==tail){ 14 q[tail++]=s[i++]; 15 }else{ 16 tail--; 17 num++; 18 } 19 } 20 } 21 q[tail]=0; 22 puts(q); 23 } 24 return 0; 25 }