[Shenji 9. Example 1] Election of the Student Union
Topic link: https://www.luogu.com.cn/problem/P1271
Title description
The school is electing student union members. There are n(n≤999) candidates, and each candidate is numbered from 1 to n. Now m(m<=2000000) votes have been collected, and each ballot is written with a candidate serial number. Now I want to sort these piles of votes in ascending order of the number of votes cast. Enter n and m and the numbers on the m ballots to find the sorted ballot numbers.
Input format
no
Output format
no
Sample input and output
Enter #1
5 10
2 5 2 2 5 2 2 2 1 2
Output #1
1 2 2 2 2 2 2 2 5 5
Problem-solving ideas:
In C++, direct quick sorting or counting sorting can solve the problem by Jesmora, but Java direct sorting may time out or over-memory QAQ, so you can consider using StringBuffer to create string buffer objects.
code show as below:
Java
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int[] a=new int[sc.nextInt()+1];
int m=sc.nextInt();
for(int i=0;i<m;i++)
a[sc.nextInt()]++;
StringBuffer s=new StringBuffer(); //创建字符串缓冲区对象,用于存储数据
for(int i=1;i<a.length;i++)
while(a[i]--!=0)
s.append(i+" "); //追加空格
System.out.println(s);
}
}
C++ (Quick Sort)
#include<iostream>
#include<algorithm>
using namespace std;
int a[2000010],n,m;
int main()
{
cin>>n>>m;
for(int i=0;i<m;i++)
cin>>a[i];
sort(a,a+m);
for(int i=0;i<m;i++)
cout<<a[i]<<" ";
return 0;
}
C++ (count sort)
#include<iostream>
using namespace std;
#define ll long long
ll b[1005],n,m,k;
int main() {
cin>>m>>n;
for(ll i=1; i<=n; ++i) {
cin>>k;b[k]++;
}
for(ll i=1; i<=m; i++) {
while(b[i]>0) {
cout<<i<<" ";
b[i]--;
}
}
return 0;
}