nth_element function usage

head File:

#include<algorithm>

usage:

nth_element(a+l,a+l+k-1,a+r+1,cmp);
nth_element(a+l,a+l+k-1,a+r+1);

effect

Array a, the interval l ~ r cmp sorted by the value of k by a small value in l + k-1 position. (E.g. 1,1,3) is a first small numbers 1, 3 is a second small number
after sorting l ~ (l + k-2 ) than the value of a [l + k-1] is small, ( l + k) ~ r than the a [l + k-1] a large, but does not guarantee the order

principle

Principle is fast row, the time complexity of O (n)


Example: sign Virgo title

Meaning of the questions: k-th largest export area of ​​the triangle:

#include<bits/stdc++.h>
using namespace std;
const double eps=1e-8;
long double  x[1000010],y[1000010];
bool cmp(long double a,long double b){
    return a-b>eps; 	//降序排序
}
long double a[1000010];
long double area(int i,int j,int k){
    return 0.5*abs(x[i]*y[j]+x[j]*y[k]+x[k]*y[i]-x[i]*y[k]-x[j]*y[i]-x[k]*y[j]);
}
int main(){
    int T;
    cin>>T;
    while(T--){
        int n,k;
        cin>>n>>k;
        for(int i=1;i<=n;++i){
            cin>>x[i]>>y[i];
        }
        int cnt=0;
        for(int i=1;i<=n;++i){
            for(int j=i+1;j<=n;++j){
                for(int k=j+1;k<=n;++k){
                  a[++cnt]=area(i,j,k);
                }
            }
        }
        int l=1,r=cnt;
        nth_element(a+l,a + k+l-1 ,a + r+1,cmp);
        printf("%.2LF\n",a[k+l-1]);
    }

    return 0;
}
Published 96 original articles · won praise 11 · views 2255

Guess you like

Origin blog.csdn.net/weixin_43769146/article/details/104213870