【枚举】Stone Pile

来源:互联网 发布:vmware windows 2016 编辑:程序博客网 时间:2024/05/17 06:58

1005. Stone Pile

Time Limit: 2.0 second
Memory Limit: 16 MB
You have a number of stones with known weights W1, …, Wn. Write a program that will rearrange the stones into two piles such that weight difference between the piles is minimal.

Input

Input contains the number of stones N (1 ≤N ≤ 20) and weights of the stones W1, …, Wn (integers, 1 ≤Wi ≤ 100000) delimited by white spaces.

Output

Your program should output a number representing the minimal possible weight difference between stone piles.

Sample

inputoutput
55 8 13 27 14
3
Problem Source: USU Championship 1997
Tags: problem for beginners  (
hide tags for unsolved problems

)


枚举。。一开始还想用矩阵乘法。。

当想到用矩阵乘法没有什么优势之后,还是放弃了,用枚举。。二进制表示

#include <cstdio>long n;long w[30];int main(){    scanf("%ld",&n);    for (long i=1;i<n+1;i++)    {        scanf("%ld",w+i);    }    long ans = 0x7f7f7f7f;    for (long i=0;i<(1<<n)+1;i++)    {        long met = i;        long cnt = 0;        for (long j=1;j<n+1;j++)        {            if (met&1) cnt+=w[j];            else cnt-=w[j];            met >>= 1;        }        if (cnt < 0) cnt = -cnt;        if (ans > cnt) ans = cnt;    }    printf("%ld",ans);}


原创粉丝点击