Ignatius and the Princess IV HDU
来源:互联网 发布:php大数据搜索 编辑:程序博客网 时间:2024/06/06 12:41
题意: 给你n个数字,让你求出出现次数为(n+1)/2 的数为多少。
思路:当时一看n有100w-1,,直接sort过了,,自己在想这怎么dp啊。。。无果就去搜百度了,,,很很高级,就是出现次数是(n+1)/2那么就是,我们先让答案ans等于最初的一个数字,如果接下来输入的数字等于ans的话我们就让计数器cnt++,不等于的话就让cnt--,当cnt==0的时候,我们就让他们变成当前输入的这个数字,这样的话我们的到的答案就一定会是出现次数大于一半大一的数字,因为和我们想要的答案的数字的和一定比其他数字大1,上代码吧:
#include <stdio.h>#include <algorithm>const int maxn = 1e7+10;using namespace std;int main(){int n;while(scanf("%d",&n)!=EOF){printf("%d\n",maxn);int ans = 0 ,t,cnt = 0 ;for(int i = 0 ; i < n ; i++){scanf("%d",&t);if(cnt == 0){ans = t;}if(ans == t){cnt++;}else {cnt--;}}printf("%d\n",ans);}}
阅读全文