題目描述
學校正在選舉學生會成員,有 n(n\le 999)n(n≤999) 名候選人,每名候選人編號分別從 1 到 nn,現在收集到了 m(m<=2000000)m(m<=2000000) 張選票,每張選票都寫了一個候選人編號。現在想把這些堆積如山的選票按照投票數字從小到大排序。輸入 nn 和 mm 以及 mm 個選票上的數字,求出排序後的選票編號。
輸入格式
無
輸出格式
無
輸入輸出樣例
輸入 #1複製
5 10 2 5 2 2 5 2 2 2 1 2
輸出 #1複製
1 2 2 2 2 2 2 2 5 5
分析:
排序篇的第一題,沒啥說的,冒牌?選擇?不行,兩百萬大小的數組在那擺着呢,想想都會超時,快排吧
啪啪啪啪,一頓手擼代碼,寫完了,不愧是練了一寒假的藍橋杯,寫快排還不是輕而易舉?
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int m;
int xp[2000005];
void quicksort(int left,int right);
int findmid(int left,int right);
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
cin>>xp[i];
quicksort(1,m);
//sort(xp+1,xp+m+1);
cout<<xp[1];
for(int i=2;i<=m;i++)
cout<<" "<<xp[i];
return 0;
}
void quicksort(int left,int right)
{
if(left>=right)
return;
int midnum=findmid(left,right);
//cout<<"mid is "<<midnum<<endl;
quicksort(left,midnum-1);
quicksort(midnum+1,right);
return ;
}
int findmid(int left,int right)
{
if(left>=right)
return left;
int high=right;
int low=left;
int temp=xp[low];
while(low<high)
{
while(low<high&&xp[high]>=temp) high--;
xp[low]=xp[high];
while(low<high&&xp[low]<=temp) low++;
xp[high]=xp[low];
}
xp[low]=temp;
return low;
}
走你,五個測試數據,超時倆???
不是吧兄弟,這是快排,還能超時?快排都超時,其他的還玩什麼?
人類迷惑大賞,沒啥說的,去看看題解吧
emmmm,大家提到了桶排序,這是什麼排序?之前沒聽過
竟然還有人用了c++STL裏的sort就AC了??????怎麼可能,我快排怎麼會比他一個自帶的sort還要慢?
一定是誤判了,快排再來一遍,還是超時,我呆了,那試試sort吧,走你,我靠,AC了?
不行,我不相信,爲什麼快排還不如一個sort?
去網上找找答案,嗯....找到了一篇,原來sort並不慢啊,是基於快排改進的函數.....是我孤陋寡聞了,我之前一直以爲自帶的sort函數時間複雜度是O(n^2),好吧,記住了,以後多用這個了,而且貌似sort比你一般手寫的快排性能還要好.....我去自閉會兒
上sort代碼
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int m;
int xp[2000005];
void quicksort(int left,int right);
int findmid(int left,int right);
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
cin>>xp[i];
//quicksort(1,m);
sort(xp+1,xp+m+1);
cout<<xp[1];
for(int i=2;i<=m;i++)
cout<<" "<<xp[i];
return 0;
}
void quicksort(int left,int right)
{
if(left>=right)
return;
int midnum=findmid(left,right);
//cout<<"mid is "<<midnum<<endl;
quicksort(left,midnum-1);
quicksort(midnum+1,right);
return ;
}
int findmid(int left,int right)
{
if(left>=right)
return left;
int high=right;
int low=left;
int temp=xp[low];
while(low<high)
{
while(low<high&&xp[high]>=temp) high--;
xp[low]=xp[high];
while(low<high&&xp[low]<=temp) low++;
xp[high]=xp[low];
}
xp[low]=temp;
return low;
}
既然提到了桶排序,那就去看看桶排序是啥,以前也沒聽說過,看到一篇博客講得不錯
https://www.cnblogs.com/bqwzx/p/11029264.html
那就實現一下吧
#include<iostream>
#include<algorithm>
using namespace std;
int n;
int m;
int xp[2000005];
int a[1000];
void quicksort(int left,int right);
int findmid(int left,int right);
int main()
{
cin>>n>>m;
for(int i=1;i<=m;i++)
cin>>xp[i];
for(int i=1;i<=m;i++)
a[xp[i]]+=1;
for(int i=1;i<=n;i++)
{
while(a[i])
{
cout<<i<<" ";
a[i]--;
}
}
return 0;
}
也AC了,看來桶排序還是有點用的,以後要多注意了