1113. Integer Set Partition (25)

来源:互联网 发布:怎么增强JS的兼容性 编辑:程序博客网 时间:2024/05/21 06:59

题目链接

这道题本来是考类快速选择的算法的,因为题目数据太弱,导致O(nlogn)的排序算法也能AC。
下面的代码可以以平均O(n)的时间复杂度找到给定数组中第k大(0<=k<n)的元素,同时以该元素将数组左右分开。

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);}

其中中枢值pivot的选择非常重要,我选择的是数组中间的元素,还可以使用随机数法选择,尽量不要选择数组的首尾元素。
另外,C++头文件algorithm中预置了一个相同功能的函数,nth_element - C++ Reference

nth_element(a,a+k,a+n);

时间复杂度也是O(n)。

下面是直接使用排序的代码。

#include<iostream>#include<algorithm>#include<cstdio>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++){    scanf("%d",&a[i]);  }  sort(a,a+n);  // nth_element(a,a+n/2,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;  return 0;}
0 0
原创粉丝点击