A1113 Integer Set Partition
#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100001;
int a[maxn];
int main()
{
int n, s1 = 0, s2 = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
sort(a, a + n);
for (int i = 0; i < n; i++)
{
if (i < n / 2) s1 += a[i];
else s2 += a[i];
}
cout << n % 2 << " " << s2 - s1 << endl;
}
快排的Partition
据说复杂度可以降到O(n)结果有个点超时了。
#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn = 100001;
int a[maxn];
int Kth_elem(int a[], int low, int high, int k) {
swap(a[low], a[(low + high) / 2]);
int pivot = a[low];
int low_temp = low, high_temp = high;
while (low < high) {
while (low < high && a[high] >= pivot) high--;
a[low] = a[high];
while (low < high && a[low] <= pivot) low++;
a[high] = a[low];
}
a[low] = pivot;
if (low == k) return a[low];
else if (low > k)
return Kth_elem(a, low_temp, low - 1, k);
else return Kth_elem(a, low + 1, high_temp, k);
}
int main()
{
int n, s1 = 0, s2 = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
Kth_elem(a, 0, n - 1, n / 2);
for (int i = 0; i < n; i++)
{
if (i < n / 2) s1 += a[i];
else s2 += a[i];
}
cout << n % 2 << " " << s2 - s1 << endl;
}