NEFU 快速排序和桶排序

快速排序

sort函数:对数组排序 sort(x,x+n) /默认升序/
升序:sort(x,x+n,less<数据类型>())
降序:sort(x,x+n,greater<数据类型>())
老和尚的导员

#include <bits/stdc++.h>
using namespace std;
struct sa
{
    int c,d,g;
    int y,h,b;
} x[110];
//cmp函数的写法
int cmp(const sa &a,const sa &b)//const是常量的意思不加可能会WA
{
    if(a.h!=b.h)
        return a.h>b.h;//返回降序,改成<可返回升序
    else if(a.c!=b.c)
        return a.c>b.c;
    else if(a.d!=b.d)
        return a.d>b.d;
    else if(a.g!=b.g)
        return a.g>b.g;
    else if(a.y!=b.y)
        return a.y>b.y;
}
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=0; i<n; i++)
        {
            cin>>x[i].c>>x[i].d>>x[i].g>>x[i].y;
            x[i].h=x[i].c+x[i].d+x[i].g+x[i].y;
            x[i].b=i+1;
        }
        sort(x,x+n,cmp);
        for(int i=0; i<n; i++)
            printf("%d %d\n",x[i].b,x[i].h);
    }
    return 0;
} 

桶排序

是计数排序,问题规模超过1e7不可使用
没必要的排序2

#include <bits/stdc++.h>
using namespace std;
int x[10000100]= {0};
int main()
{
    int n,k;
    cin>>n>>k;
    int y[100100]= {0},res=0,num=0;
    for(int i=1; i<=n; i++)
    {
        cin>>x[i];
        y[x[i]]++;//将数存入对应的下标实现桶排序
    }
    for(int i=1e5; i>=1; i--)
    {
        if(y[i]>0)
        {
            res=res+y[i]*i;
            num=num+y[i];
        }
        if(num>=k)
        {
            res=res-(num-k)*i;
            break;
        }
    }
    cout<<res;
    return 0;
}

发布了13 篇原创文章 · 获赞 0 · 访问量 397

猜你喜欢

转载自blog.csdn.net/qq_46126537/article/details/103897320