zoukankan      html  css  js  c++  java
  • 选择问题(分治策略)

    选择问题(Selection Problem),即在n个元素的集合中寻找第K小的元素的问题。第K小的元素又叫第K个顺序统计量。有以下几种变体: 
    - 找最大值和最小值;同时找最大和最小值 
    - 找中位数(第n/2小) 
    - 找任意第K小的元素 
    - 找Top-K的元素

     1 //选择问题
     2 #include<iostream>
     3 #include<cstdio>
     4 #include<cstdlib>
     5 #include<algorithm>
     6 using namespace std;
     7 int a[1001];
     8 
     9 int select(int left,int right,int k){
    10     if( left >= right )
    11         return a[left];
    12     int x = a[left];
    13     int i = left;
    14     int j = right+1;
    15     while( true ){
    16         do{
    17             i++;
    18         }while(a[i]<x);
    19         do{
    20             j--;
    21         }while(a[j]>x);
    22         if( i>=j )
    23             break ;
    24         swap(a[i],a[j]);
    25     }
    26     if( j-left+1 == k )
    27         return x;
    28     a[left] = a[j];
    29     a[j] = x;
    30     if( j-left+1 < k )
    31         return select(j+1,right,k-j+left-1);
    32     else
    33         return select(left,j-1,k); 
    34 }
    35 
    36 int main(){
    37     int n;
    38     while( scanf("%d",&n) != EOF ){
    39         int k;
    40         cin>>k;
    41         for( int i = 0; i < n; i++ )
    42             cin>>a[i];
    43         cout<<select(0,n-1,k)<<endl;
    44     }
    45     return 0;
    46 }

  • 相关阅读:
    day7
    11.3NOIP模拟赛
    codeforces 880E. Maximum Subsequence(折半搜索+双指针)
    11.2NOIP模拟赛
    bzoj1483: [HNOI2009]梦幻布丁(vector+启发式合并)
    day9
    codeforces 1006 F(折半搜索)
    codeforces 28D(dp)
    P2210 Haywire(A*)
    4800: [Ceoi2015]Ice Hockey World Championship(折半搜索)
  • 原文地址:https://www.cnblogs.com/geziyu/p/10029877.html
Copyright © 2011-2022 走看看