01背包简单题,只不过要用Java写,写了比较久一点
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
int score[] = new int[num];
int time[] = new int[num];
for (int i = 0; i < num; i++) {
score[i] = scanner.nextInt();
}
for (int i = 0; i < num; i++) {
time[i] = scanner.nextInt();
}
int totalTime = scanner.nextInt();
System.out.println(getScore(score, time, totalTime, num));
}
public static int getScore(int score[], int time[], int totalTime, int size) {
int num[] = new int[totalTime + 10];
for (int a = 0; a < size; a++)
for (int b = totalTime; b - time[a] >= 0; b--)
num[b] = Math.max(num[b], num[b - time[a]] + score[a]);
return num[totalTime];
}
}
输入:
4
9 7 5 3
10 8 5 2
典型的贪心算法,可以参考田忌赛马
import java.util.Scanner;
import java.util.Arrays;
public class Main {
public static void main(String[] arg) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] teamA = new int[n];
int[] teamB = new int[n];
for (int i = 0; i < n; i++) {
teamA[i] = scanner.nextInt();
}
for (int i = 0; i < n; i++) {
teamB[i] = scanner.nextInt();
}
System.out.println(getMostBonus(n, teamA, teamB));
}
public static int getMostBonus(int n, int teamA[], int teamB[]) {
Arrays.sort(teamA);
Arrays.sort(teamB);
int n1 = 0, n2 = 0, l1 = n - 1, l2 = n - 1, j1 = 0, j2 = 0;
for (int a = 0; a < n; a++) {
if (teamA[n1] > teamB[n2]) {
n1++;
n2++;
j1++;
}
else if (teamA[n1] < teamB[n2]) {
j2++;
n1++;
l2--;
}
else {
if (teamA[l1] > teamB[l2]) {
j1++;
l1--;
l2--;
}
else if (teamA[n1] < teamB[l2]) {
j2++;
n1++;
l2--;
}
else
break;
}
}
return j1 * 100 - j2 * 100;
}
}