HDU 1029 Ignatius and the Princess IV (水)

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1029

题意:给n个数,n保证是奇数,求出现次数,大于(n+1)/2的数。

题解:由题意可知,一定存在数字出现的次数大于(n+1)/2次,排序后(n+1)/2位置一定就是结果=-=。

不理解可以画个图理解一下。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1e6+7;
int a[maxn];
int main(){
	int n;
	while(~scanf("%d",&n)){
		for(int i = 0 ; i < n ; i ++)
			scanf("%d",&a[i]);
		sort(a,a+n);
		printf("%d\n",a[(n+1)/2]);
	}
}

猜你喜欢

转载自blog.csdn.net/PK__PK/article/details/81476941
今日推荐