删数问题:键盘输入一个高精度正整数N,去掉其中任意S个数字后剩下的数字按原左右次序组成一个新的正整数。编程对给定的N和S,寻找一种方案使得剩下的数字组成的新数最小。
贪心法:每次找递减序列,删掉序列的头数字。
代码:
/***
* starstarstarpku@gmail.com
* 20080402
*
* given 2 integers N and S, delete S numbers of N, in order that
* the remain integer is the smallest.
*
* greedy strategy
* 0) from beginning of N, find the decrease sequence Ds,
* 1) if not found, delete the last number of N;
* 2) otherwise, delete the first number of Ds;
* 3) goto 0), until we have deleted S numbers;
*
* note that N is rather large, may be as long as 240.
*/
#include <iostream>
#include <string>
using namespace std;
#define LENGTH 256
void solve ()
{
char p[LENGTH];
int n, s;
cin >>p >> s;
n = strlen(p);
int cnt=0;
while (cnt < s) {
int max=0;
while (max < n && p[max] == 'x')
max++;
int i = max;
while (i<n && (p[i] == 'x' || p[i]>=p[max])) {
if (p[i] != 'x')
max = i;
i++;
}
cout << "delete " <<max<<" "<<p[max]-'0'<<endl;
p[max]='x';
cnt++;
for (int j=0; j<n; j++)
cout << p[j];
cout << endl;
}
// output result number
for (int j=0; j<n; j++) {
if (p[j] != 'x')
cout << p[j];
}
cout << endl;
}
int main (int argc, char **argv)
{
solve ();
return 0;
}
贪心法:每次找递减序列,删掉序列的头数字。
代码:
/***
* starstarstarpku@gmail.com
* 20080402
*
* given 2 integers N and S, delete S numbers of N, in order that
* the remain integer is the smallest.
*
* greedy strategy
* 0) from beginning of N, find the decrease sequence Ds,
* 1) if not found, delete the last number of N;
* 2) otherwise, delete the first number of Ds;
* 3) goto 0), until we have deleted S numbers;
*
* note that N is rather large, may be as long as 240.
*/
#include <iostream>
#include <string>
using namespace std;
#define LENGTH 256
void solve ()
{
char p[LENGTH];
int n, s;
cin >>p >> s;
n = strlen(p);
int cnt=0;
while (cnt < s) {
int max=0;
while (max < n && p[max] == 'x')
max++;
int i = max;
while (i<n && (p[i] == 'x' || p[i]>=p[max])) {
if (p[i] != 'x')
max = i;
i++;
}
cout << "delete " <<max<<" "<<p[max]-'0'<<endl;
p[max]='x';
cnt++;
for (int j=0; j<n; j++)
cout << p[j];
cout << endl;
}
// output result number
for (int j=0; j<n; j++) {
if (p[j] != 'x')
cout << p[j];
}
cout << endl;
}
int main (int argc, char **argv)
{
solve ();
return 0;
}