这道题做得很郁闷,思路很好懂,可是做得时候总是出问题,到现在也不知道最开始那种写法问题在什么地方。
#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;
}