Boxers CodeForces - 1203E (贪心解法)——26行代码AC

立志用更少的代码做更高效的表达


There are n boxers, the weight of the i-th boxer is ai. Each of them can change the weight by no more than 1 before the competition (the weight cannot become equal to zero, that is, it must remain positive). Weight is always an integer number.

It is necessary to choose the largest boxing team in terms of the number of people, that all the boxers’ weights in the team are different (i.e. unique).

Write a program that for given current values ​ai will find the maximum possible number of boxers in a team.

It is possible that after some change the weight of some boxer is 150001 (but no more).

Input
The first line contains an integer n (1≤n≤150000) — the number of boxers. The next line contains n integers a1,a2,…,an, where ai (1≤ai≤150000) is the weight of the i-th boxer.

Output
Print a single integer — the maximum possible number of people in a team.

Input
4
3 2 4 1

Output
4

Input
6
1 1 1 4 4 4

Output
5


题意:有n个拳击运动员,每个人在比赛前可以改变一斤体重,询问比赛时最多能带几个不同体重的运动员。

思路:使用优先队列将序列降序排序(O(nlogn)), 然后定义a数组判断这个值是否出现过, 先判断+1, 然后判断该数,最后-1(-1的情况下不能为1)。

若想升序排序,则过程相反。

贪就完了


代码展示

#include<bits/stdc++.h> 
using namespace std;
int a[150005];
int main() {
	ios::sync_with_stdio(false);
	int n; while(cin>>n) {
		priority_queue<int, vector<int>, less<int> >q;	//降序队列 
		for(int i = 0; i < n; i++) { 
			int x; cin>>x;
			q.push(x);
		}
		memset(a, 0, sizeof(a));		//重置a数组 
		
		for(int i = 0; i < n; i++) {
			int x; x = q.top();
			if(a[x+1] == 0) a[x+1] = 1;
			else if(a[x]==0) a[x] = 1;
			else if(a[x-1]==0 && x!=1) a[x-1] = 1;
			q.pop();
		}
		
		int num=0;
		for(int i = 0; i < 150005; i++) {
			if(a[i] == 1)  num++;
		}
		cout << num << endl; /* */
	}
return 0; }

博主的碎碎念

时隔多天终于重拾ACM开始敲代码, 连EOF格式都用不熟练了, 汗-_-||,这道水题也是整整思考了一个小时才跌跌撞撞的A出来。 大家千万不要像我一样啊! 平时一定要跟住训练, 一日只练一日功,一日不练十日空!

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 像素格子 设计师:CSDN官方博客 返回首页