hdoj 1029 Ignatius and the Princess IV

来源:互联网 发布:sql替换部分字符串 编辑:程序博客网 时间:2024/05/01 04:50

题目:http://acm.hdu.edu.cn/showproblem.php?pid=1029


用排序水过,一个数在一个序列中占一半以上的话如果排好序,中间的位置肯定是它,类似于鸽巢原理

#include<cstdio>#include<algorithm>using namespace std;int arr[1000000];int main(){    int N;    while(scanf("%d", &N)!=EOF)    {        for(int i = 0; i < N; ++i)            scanf("%d", arr+i);        sort(arr, arr+N);        printf("%d\n", arr[N/2]);    }    return 0;}

在Discuss里看到一个代码写的不错,O(N)搞定,贴出来大家品味一下

#include<iostream>#include<vector>#include<algorithm>using namespace std ;int main( void ){int n,max,m,count;while(cin>>n){    count=0;for(int i=0;i<n;i++){cin>>m;if(count==0){max=m;count++;}else{if(m!=max)count--;else count++;}}cout<<max<<endl;}return 0;}

OJ给出的快排执行时间是281MS,执行内存是1392K,而笔者用类似上面O(N)解法的执行时间和内存分别是218MS和1388K,看来STL的sort应该优化了不少,不然O(N)的效率应该比O(NlogN)的效率好的不止这么一点的。

这其实就是排序查找的top 1,联想到排序查找中的top k的话,其时间复杂度是O(N*K)

原创粉丝点击