[codility]Min-abs-sum
生活随笔
收集整理的這篇文章主要介紹了
[codility]Min-abs-sum
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
https://codility.com/demo/take-sample-test/delta2011/
0-1背包問題的應用。我自己一開始沒想出來。“首先對數組做處理,負數轉換成對應正數,零去掉,計數排序統計有多少個不同元素及其對應個數,并累加所有數的和sum,不妨記b=sum/2,不同元素個數為m,則目標轉換為在m個不同元素中挑出若干個元素(每個元素可以重復多次,但少于它們的出現次數),使得它們的和不大于b并盡量接近。到了這里,應該有點熟悉的感覺了吧。對了,其實這就是0-1背包問題!” 參考http://phiphy618.blogspot.jp/2013/05/codility-delta-2011-minabssum.html
第一次的代碼并未完全通過,75分,大數據全掛。原因是這里一個元素可以出現多次,是多重背包問題。
// you can also use imports, for example: // import java.math.*; class Solution {public int solution(int[] A) {// write your code here...if (A.length == 0) return 0;int sum = 0;int max = 0;for (int i = 0; i < A.length; i++) {if (A[i] < 0) A[i] = -A[i];sum += A[i];}int target = sum / 2;int dp[][] = new int[A.length][target];for (int i = 0; i < A.length; i++) {for (int j = 0; j < target; j++) {// j+1 is the weight limitif (i == 0){if (A[i] <= (j+1)) {dp[i][j] = A[i];}else{dp[i][j] = 0;}}else // i != 0{int w1 = dp[i-1][j];int w2 = 0;if (j-A[i] >=0 ) {w2 = dp[i][j-A[i]] + A[i];}dp[i][j] = w1 > w2 ? w1 : w2;}}}max = dp[A.length - 1][target - 1];return (sum - max * 2);} }第二次參考了cp博士的文章,處理了多重背包的優化,并用了滾動數組:http://blog.csdn.net/caopengcs/article/details/10028269
// you can also use includes, for example: // #include <algorithm> int solution(const vector<int> &A) {// write your code in C++98int len = A.size();int sum = 0;int M = 0;for (int i = 0; i < len; i++) {int x = 0;x = A[i] > 0 ? A[i] : -A[i];sum += x;if (x > M)M = x;}vector<int> count;count.resize(M+1);for (int i = 0; i < len; i++) {int x = 0;x = A[i] > 0 ? A[i] : - A[i];count[x]++;}int target = sum / 2;int largest = 0;vector<int> dp(target+1, -1);for (int i = 0; i <= M; i++) {if (count[i] > 0) {for (int j = 0; j <= target; j++) {if (j == 0) dp[j] = count[i];if (dp[j] >= 0) {dp[j] = count[i];if (j > largest)largest = j;}else if (j - i >= 0 && dp[j - i] > 0) {dp[j] = dp[j - i] - 1;if (j > largest)largest = j;}else {dp[j] = -1;}}}}return abs(sum - 2 * largest); }
轉載于:https://www.cnblogs.com/lautsie/p/3228644.html
總結
以上是生活随笔為你收集整理的[codility]Min-abs-sum的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 累
- 下一篇: javascript-04 引用类型