2018 完美世界校招笔试编程题(Java)

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;
	}
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值