九度 1420 Jobdu MM分水果 -- 动态规划、深度优先搜索

题目地址:http://ac.jobdu.com/problem.php?pid=1420

 

题目描述:

Jobdu团队有俩PPMM,这俩MM干啥都想一样。一天,富强公司给团队赞助了一批水果,胡老板就把水果派发给了这俩MM,由她们自行分配。每个水果都有一个重量,你能告诉她们怎么分才使得分得的重量差值最小吗?

输入:

输入有多组数据,每组数据第一行输入水果个数n(1<=n<=100),接下来一行输入n个重量wi(0<=wi<=10^5)。

输出:

对每组输入输出一行,输出可以得到的最小差值。

样例输入:
510 20 30 10 10 
样例输出:
0

 

 

0/1背包解法:

 

//题目地址:http://ac.jobdu.com/problem.php?pid=1420
#include <stdio.h>
#include <string.h>

#define Max(a, b) (a > b)?(a):(b);

int n, sum;
int fruit[100];
int dp[5000001];

int MinDiff(){
    int i, j;
    int first, second, ans;
    int half = (sum >> 1);
    memset(dp, 0, sizeof(dp));
    for (i = 0; i < n; ++i){
        for (j = half; j >= fruit[i]; --j){
            dp[j] = Max(dp[j], dp[j-fruit[i]] + fruit[i]);
        }
    }
    return sum - 2 * dp[half];
}
int main(int argc, char *argv[]) {
    int i;
    while (scanf("%d", &n) != EOF){
        sum = 0;
        for (i = 0; i < n; ++i){
            scanf("%d", &fruit[i]);
            sum += fruit[i];
        }
        printf("%d\n", MinDiff());
    }
    return 0;
}
/**************************************************************
Problem: 1420
User: 简简单单Plus
Language: C
Result: Accepted
Time:1170 ms
Memory:20444 kb
****************************************************************/        

 

 

深度优先搜索解法:

#include <stdio.h>
#include <string.h>

int n, k, fruit[100], used[100], total, half;

void dfs(int x, int y) {
    int i;
    if (y > half) return;
    if (y > k) k = y;
    if (k == half) return;
    for (i = x; i < n; i++)
      if (!used[i]) {
        used[i] = 1;
        dfs(i + 1, y + fruit[i]);
        used[i] = 0;
    }
}

int main() {
    int i;
    while(scanf("%d",&n) != EOF) {
        total = 0;
        for(i = 0;i < n; i++) {
            scanf("%d", &fruit[i]);
            total += fruit[i];
        }
        k = -1;
        half = total >> 1;
        memset(used, 0, sizeof(used));
        dfs(0, 0);
        printf("%d\n", total- k * 2);
    }
    return 0;
}
/**************************************************************
Problem: 1420
User: 简简单单Plus
Language: C
Result: Accepted
Time:50 ms
Memory:916 kb
****************************************************************/                                    

 

 

 

 


 

posted @ 2014-03-15 11:43  liushaobo  阅读(354)  评论(0编辑  收藏  举报