新农上路
- 积分
- 99
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-6-2
- 最后登录
- 1970-1-1
|
0-1 背包问题,用C++实现了一下,如果A不可能赢一个州的选举人票(比如,B已经赢了该州),直接跳过。
没有编译和测试,欢迎大家指出问题。
- /*
- check if A can win election
- find min votes needed for A to win
- calculate min votes needed to win each state
- calculate min votes needed to win majority of electors
- 0/1 knapsack problem
- Time Complexity: O(m * n)
- Space Complexity: O(m * n)
- m: number of states
- n: total number of electors
- */
- int minVotesToWin(int numStates,
- const vector<int>& electors,
- const vector<int>& votesA,
- const vector<int>& votesB,
- const vector<int>& votesUndecided) {
- // validate parameters
- if (numStates <= 0 || numStates != electors.size() || numStates != votesA.size() || …) {
- throw invalid_arguments(“”);
- }
- int totalElectors = accumulate(electors.begin(), electors.end(), 0);
- int electorsA = 0;
- vector<int> minVotes(numStates, INT_MAX);
- for (int i = 0; i < numStates; ++i) {
- int votes = votesA[i] + votesB[i] + votesUndecided[i];
- int majority = votes / 2 + 1;
- if (votesA[i] + votesUndecided[i] >= majority) {
- electorsA += electors[i];
- minVotes[i] = majority - votesA[i];
- }
- }
- if (electorsA < totalElectors / 2 + 1) {
- return INT_MAX;
- }
- // 0-1 knapsack
- // table[i][j] : min votes needed to win j electors from first i states
- // table[i][j] = max(table[i-1][j], table[i-1][j-minVotes[i-1]] + minVotes[i-1])
- vector<vector<int>> table(numStates, vector<int>(totalElectors + 1, INT_MAX));
- for (int i = 0; i < numStates; ++i) {
- table[i][0] = 0;
- }
- for (int j = 0; j <= totalVotes; ++j) {
- table[0][j] = 0;
- }
- for (int i = 1; i < numStates; ++i) {
- for (int j = 1; j <= totalElectors; ++j) {
- int votes1 = INT_MAX, votes2 = INT_MAX;
- if (j >= electors[i] && minVotes[i-1] != INT_MAX) {
- votes1 = table[i-1][j-electors[i-1]] + minVotes[i-1];
- }
- votes2 = table[i-1][j];
- table[i][j] = min(votes1, votes2);
- }
- }
- int result = INT_MAX;
- for (int j = totalVotes / 2 + 1; j <= totalVotes; ++j) {
- result = min(result, minVotes[j]);
- }
- return result;
- }
复制代码 |
|