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
- 1113. Integer Set Partition (25)
- 1113. Integer Set Partition (25)
- 1113. Integer Set Partition (25)
- 1113. Integer Set Partition (25)
- 1113. Integer Set Partition (25)
- 1113. Integer Set Partition (25)
- 1113. Integer Set Partition (25)
- 1113. Integer Set Partition (25)
- 1113. Integer Set Partition (25)
- 1113. Integer Set Partition (25)
- 1113. Integer Set Partition (25)
- 1113. Integer Set Partition
- 1113. Integer Set Partition
- PAT_A 1113. Integer Set Partition (25)
- pat 1113. Integer Set Partition (25)
- 1113. Integer Set Partition (25) PAT 甲级
- PAT 甲级 1113. Integer Set Partition (25)
- PAT--1113. Integer Set Partition
- 用空瓶和瓶盖换酒喝
- PHP文件上传的实现及其介绍
- 最长公共子序列,记忆化搜索
- HTTPS原理
- 【C++】《More Effective C++》读书笔记(转载+修订)
- 1113. Integer Set Partition (25)
- 狸猫的笔试——格雷码判断
- The 11th Zhejiang Provincial Collegiate Programming Contest
- 九度 1007
- UVA 1452Jump 【约瑟夫环】
- Boostrap框架学习总结
- findChessboardCorners函数学习笔记
- 【复习笔记】 cocos2d-x 2.x 渲染特效实现 六 节点树的描边效果
- 1004