删数问题
键盘输入一个高精度的正整数n(<=240位),
去掉任意s个数字后剩下的数字按原左右次序将组成一个新的正整数。
编程对给定的n和s,寻找一种方案,使得剩下的数最小。
Simple Input
178543
4
Simple Output
13
思路1:
每一步总是选择一个使剩下的数最小的数字删除,即按高位到低位的顺序搜索,若各位数字递增,则删除最后一个数字;否则删除第一个递减区间的首字符,这样删一位便形成了一个新的数字串。然后回到串首,按上述规则再删除下一个数字
参考借鉴代码1:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string n;
int s,i,x,l,m;
while(cin>>n>>s)
{
i=-1,m=0,x=0;
l=n.length();
while(x<s&&m==0)
{
i++;
if(n[i]>n[i+1])//出现递减,删除递减的首数字
{
n=n.erase(i,1);
x++;// x统计删除数字的个数
i=-1;//从头开始查递减区间
}
if(i==l-x-2&&x<s)
m=1;//已经无递减区间,m=1脱离循环
}
cout<<n.substr(0,l-s+x)<<endl;//只打印剩下的左边l-(s-x)个数字
}
return 0;
}
笔者思路2:
123456……
源代码2:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <process.h>
#include <math.h>
int main()
{
char a[100];
int k; //k个数
int n; //数字位数
int head, tail; //可选区间开头和结尾
int i = 0, besti; //循环变量
char min;
gets(a);
scanf("%d",&k);
while(a[i] != '\0')
i ++;
n = i;
printf("所输入数的位数为:%d\n", i);
printf("所输入的数:");
for(i = 0; i < n; i ++)
printf("%c", a[i]);
printf("\n\n");
head = 0;
besti = 0;
//printf("%c\n", a[n-k]);
//printf("%c\n", a[n-1]);
for(tail = n-k; tail <= n-1; tail ++)
{
besti = head;
min = '9';
for(i = head; i <= tail; i ++)
if(a[i] < min)
min = a[i];
for(i = head; i <= tail; i ++)
{
if(a[i] == min)
{
besti = i;
break;
}
}
printf("第-%d-轮选择的是第-%d-位数字:", tail-n+k+1, besti+1);
printf("%c\n\n", a[besti]);
head = besti + 1;
}
return 0;
}
/*
213854367922451852
6
121852
*/