URAL 1026 - Questions and Answers(計數排序)

整數的範圍只有1到5000,所以開個5000的數組,記錄一下每個數出現的個數即可

複雜度爲O(k*5000),效率比較高

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

int a[5050];
int main()
{
    char s[5];
    int n,x,k;
    scanf("%d",&n);
    memset(a,0,sizeof(a));
    while(n--)
    {
        scanf("%d",&x);
        a[x]++;
    }
    scanf("%s",s);
    for(int i=1;i<=5000;i++)
        a[i]+=a[i-1];
    scanf("%d",&k);
    while(k--)
    {
        scanf("%d",&x);
        for(int i=1;i<=5000;i++)
        if(a[i]>=x)
        {
            printf("%d\n",i);
            break;
        }
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章