http://nnsznoi.openjudge.cn/sysffx/02/
-
总时间限制:
- 1000ms 内存限制:
- 1024kB
-
描述
-
输入一个高精度正整数N,去掉其中任S个数字后剩下的数字按原左右次序组成一个新的正整数,编程对给定的N和S,寻找一种方法使剩下的数字组成的新数最小
输入
- 两个一个高精度数(长度小于255) s 输出
- 最小的新数 样例输入
-
174 1
样例输出
-
14
package Greedy;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
/**
* 考虑只删一个数的情况,最优解是删除出现的第一个左边>右边的数,因为删除之后高位减小,很容易想...那全局最优解也就是这个了,
* 因为删除S个数字就相当于执行了S次删除一个数,因为留下的数总是当前最优解
*
*/
public class DeleteNumber {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc = new Scanner(System.in);
// File file = new File("src/Greedy/DeleteNumber.in");
// Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int N = sc.nextInt();
int S = sc.nextInt();
System.out.println(greedy(N, S));
}
}
public static String greedy(int N, int S) {
StringBuffer sb = new StringBuffer(N + "");
boolean del = false; // 表示
for (int i = S; i > 0; i--) {
del = false;
// 每次删除第一个比下一个数字大的数
for (int j = 0; j < sb.length() - 1; j++) {
if (sb.charAt(j) > sb.charAt(j + 1)) {
sb.delete(j, j + 1);
del = true;
break;
}
}
// 如果所有数字递增,则删除最后几个数字直接返回
// 如123 -> 12
if (del == false) {
sb.delete(sb.length() - i, sb.length());
}
}
return sb.toString();
}
}
1万+

被折叠的 条评论
为什么被折叠?



