您的位置:首页 > 其它

Ural1005-Stone Pile

2016-11-15 14:02 274 查看
给出n个数,要求将其分成两堆,求两堆数字总和的差值最小。

一开始傻傻的用next_permutation,第二个数据就TLE了….

其实搜索每个元素,先放在一堆搜索,再回溯放在另一堆搜索,复杂度为2^20.

#include <cstdio>
#include <cmath>
#include <cstdlib>

const int INF = 20 * 100000;

int a[25];
bool mark[25];

int n;
int ans = INF;

void dfs(int x) {
if (x == n - 1) {
int s = 0, t = 0;
for (int i = 0; i < n; i++) {
if (mark[i]) {
s += a[i];
} else {
t += a[i];
}
}
if (abs(s - t) < ans) {
ans = abs(s - t);
}
return;
}
mark[x] = true;
dfs(x+1);
mark[x] = false;
dfs(x+1);
}

int main(int argc, char const *argv[]) {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
dfs(0);
printf("%d\n", ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: