Subset
| Time Limit: 30000MS | Memory Limit: 65536K | |
| Total Submissions: 4032 | Accepted: 781 |
Description
Given a list of N integers with absolute values no larger than 10
15, find a non empty subset of these numbers which minimizes the absolute value of the sum of its elements. In case there are multiple subsets, choose the one with fewer elements.
Input
The input contains multiple data sets, the first line of each data set contains N <= 35, the number of elements, the next line contains N numbers no larger than 10
15 in absolute value and separated by a single space. The input is terminated with N = 0
Output
For each data set in the input print two integers, the minimum absolute sum and the number of elements in the optimal subset.
Sample Input
1 10 3 20 100 -100 0
Sample Output
10 1 0 2
Source
题意:给你n个数,从中选出一些数,使得他们的和的绝对值最小,有多个的话选出数的数量最少
解题思路:将所有数分为前后两部分,用状压的方法枚举出前面一段所有的组成可能,然后将它们根据它们的和进行排序,和相同的根据数字的个数排序,暴力枚举后面一段,二分查找前一段和它的组合,使它们和的绝对值小
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <set>
using namespace std;
#define LL long long
struct node
{
LL sum;
int cnt;
}x[300000], ans;
LL a[300000];
int n,mid;
LL Abs(LL x)
{
return x>0 ? x : -x;
}
bool cmp(node a, node b)
{
if (a.sum != b.sum) return a.sum < b.sum;
else return a.cnt < b.cnt;
}
void check(LL sum, int cnt)
{
int l = 0, r = (1 << mid) - 1,ans1=-1;
while (l <= r)
{
int mid1 = (l + r) >> 1;
if (x[mid1].sum < -sum) { l = mid1 + 1, ans1 = mid1; }
else r = mid1 - 1;
}
ans1++;
if (ans1 < (1 << mid))
{
if (Abs(ans.sum) > Abs(x[ans1].sum + sum)) ans.sum = x[ans1].sum + sum, ans.cnt = x[ans1].cnt + cnt;
if (Abs(ans.sum) == Abs(x[ans1].sum + sum) && ans.cnt > x[ans1].cnt + cnt)ans.cnt = x[ans1].cnt + cnt;
}
ans1--;
while (1)
{
if (ans1 == 0 || x[ans1].sum != x[ans1 - 1].sum) break;
ans1--;
}
if (Abs(ans.sum) > Abs(x[ans1].sum + sum)) ans.sum = x[ans1].sum + sum, ans.cnt = x[ans1].cnt + cnt;
if (Abs(ans.sum) == Abs(x[ans1].sum + sum) && ans.cnt > x[ans1].cnt + cnt)ans.cnt = x[ans1].cnt + cnt;
}
int main()
{
while (scanf("%d", &n)&&n)
{
for (int i = 0; i < n; i++) scanf("%lld", &a[i]);
mid = n >> 1;
ans.sum=Abs(a[0]),ans.cnt=1;
for (int i = 0; i < (1 << mid); i++)
{
x[i].cnt = 0,x[i].sum = 0;
for (int j = 0; j < mid; j++)
if ((1 << j)&i) { x[i].cnt++, x[i].sum +=a[j]; }
if (i&&Abs(ans.sum) > Abs(x[i].sum)) ans = x[i];
else if (i&&Abs(ans.sum) == Abs(x[i].sum)&&ans.cnt > x[i].cnt) ans = x[i];
}
sort(x, x + (1 << mid),cmp);
for (int i = 1; i < (1 << (n - mid)); i++)
{
LL sum = 0;
int cnt = 0;
for (int j = 0; j < n - mid; j++)
if ((1 << j)&i) {cnt++;sum += a[mid + j];}
check(sum, cnt);
}
printf("%lld %d\n", Abs(ans.sum), ans.cnt);
}
}

本文介绍了一道算法题目,任务是找到一个整数集合的非空子集,使得这些元素之和的绝对值最小;若存在多个解,则选择元素数量最少的那个。通过将集合分为两部分并使用状态压缩枚举所有可能的组合,再利用二分查找来优化搜索过程。
882

被折叠的 条评论
为什么被折叠?



