programming-challenges Ferry Loading (111106) 题解

这道题做得很郁闷,思路很好懂,可是做得时候总是出问题,到现在也不知道最开始那种写法问题在什么地方。

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <assert.h>
#include <algorithm>
#include <math.h>
#include <ctime>
#include <functional>
#include <string.h>
#include <stdio.h>
#include <numeric>
#include <float.h>

using namespace std;

const int MXLEN = 10010; 
const int MXNUM = 110; 

bool dp[2100][20010];
int pre[2100][20010];

void solution(int totalLength, vector<int> &cars) {
	memset(dp, 0, sizeof(dp));
	memset(pre, 0, sizeof(pre));

	int maxNum = 0, maxLength1 = 0;
	int currentLength = 0; 
	dp[0][0] = true;

	for (int i = 0; i < cars.size(); i++) {
		if (i > 200) break;
		currentLength += cars[i]; 
		int carNum = i + 1; 
		for (int j = 0; j <= totalLength; j++) {
			if (j >= cars[i] && dp[i][j - cars[i]]) {
				maxNum = carNum; 
				dp[carNum][j] = true;
				pre[carNum][j] = 1;
				maxLength1 = j; 
			}
			else if ((currentLength - j) <= totalLength && dp[i][j]) {
				maxNum = carNum;
				dp[carNum][j] = true;
				pre[carNum][j] = 2; 
				maxLength1 = j; 
			}

			/*
			why this is wrong?
			if (dp[i][j]) {
				if ((j + cars[i]) <= totalLength) {
					dp[carNum][j + cars[i]] = true;
					maxNum = carNum; 
					maxLength1 = j + cars[i];
					pre[carNum][maxLength1] = 1;
				}
				
				if (!dp[carNum][j] && (currentLength - j) <= totalLength) {
					dp[carNum][j] = true;
					maxNum = carNum; 
					maxLength1 = j;
					pre[carNum][maxLength1] = 2; 
				}
			}
			*/
			
		}
	}

	cout << maxNum << endl;
	vector<string> solution;
	while (maxNum > 0) {
		if (pre[maxNum][maxLength1] == 1) {
			solution.push_back("port");
			maxLength1 -= cars[maxNum - 1];
		}
		else {
			solution.push_back("starboard");
			; 
		}
		maxNum--; 
	}
	for (int i = solution.size() - 1; i >= 0; i--) {
		cout << solution[i] << endl;
	}
}

int main() {
	int T = 0; cin >> T; 
	for (int t = 0; t < T; t++) {
		vector<int> cars;
		int totalLength = 0; cin >> totalLength; totalLength *= 100; 
		int len = 0; 
		while (cin >> len) {
			if (len == 0) break;
			cars.push_back(len);
		}
		if (t > 0) cout << endl; 
		solution(totalLength, cars);
	}

	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值