1113 Integer Set Partition(25分)

题目翻译:

给出一个集合,将其分为两个互斥的集合,要求两个集合的元素数目相差最小、元素总和相差最大

题解思路:

  1. 先排序;
  2. n为偶数:对半分;
  3. n为奇数:中间值给大集合;

代码:

#include
using namespace std;

int main()
{
	int N;
	vector a;
	cin >> N;
	for (int i = 0;i < N;i++)
	{
		unsigned long long temp;
		cin >> temp;
		a.push_back(temp);
	}
	sort(a.begin(), a.end());
	unsigned long long S1=0, S2=0;
	if (N % 2)//奇数
	{
		for (int i = 0;i < (N - 1) / 2;i++)
			S1 += a[i];
		for (int i = (N - 1) / 2;i < N;i++)
			S2 += a[i];
		cout << 1 << " " << S2 - S1;
	}
	else
	{
		for (int i = 0;i <= N / 2 - 1;i++)
			S1 += a[i];
		for (int i = N / 2;i < N;i++)
			S2 += a[i];
		cout << 0 << " " << S2 - S1;
	}
}

坑点:

你可能感兴趣的:(数据结构)