P1271题解

发布时间 2024-01-09 22:10:07作者: Rayliuliu

博文T4航站楼 ✈ P1271【深基9.例1】选举学生会

预先准备

本题需要用到排序函数 sort,不会者参看文章sort用法

头文件 #include<algorithm>

还需用到一个数组 a[2000005]

思路

1.定义及输入 n,m :选举人数/投票人数

int n,m;
cin>>n>>m;

2.循环输入数组

for(int i=1;i<=m;i++){
   cin>>a[i];
}

3.排序:格式 sort(数组+起始下标,数组+结束下标+1,排序方法);(不加排序方法则默认从小到大)

sort(a+1,a+m+1);

4.循环输出数组

for(int i=1;i<=m;i++){
   cout<<a[i]<<" ";
}

至此,这道题就做完了。完整代码看下面

完整代码

#include<iostream>
#include<algorithm>
using namespace std;
int a[2000005];
int main(){
	int n,m;
	cin>>n>>m;
	for(int i=1;i<=m;i++){
		cin>>a[i];
	}
	sort(a+1,a+m+1);
	for(int i=1;i<=m;i++){
		cout<<a[i]<<" ";
	}
	return 0;
}