hdu 1029 Ignatius and the Princess IV
来源:互联网 发布:很火excuse me网络意思 编辑:程序博客网 时间:2024/06/05 04:55
题目链接:点击打开链接
题意:找出长度为奇数的序列中,出现次数>=(N+1)/2的数
法一:排序,中位数即为所求
#include <cstdio>#include <algorithm>#include <iostream>using namespace std;int a[1000005];int main(){int n;while(scanf("%d",&n)!=EOF){for(int i=0;i<n;i++){scanf("%d",&a[i]);}sort(a,a+n);printf("%d\n",a[n/2]);}return 0;}法二:哈希映射
#include <cstdio>#include <algorithm>#include <iostream>#include <map>using namespace std;int main(){int n,num,re;map<int,int> m;while(scanf("%d",&n)!=EOF){m.clear();for(int i=0;i<n;i++){scanf("%d",&num);m[num]++;if(m[num]>=(n+1)/2){re=num;}}printf("%d\n",re);}return 0;}法三:之前接触过的方法,自己实现了一波,先把数放到队列里,两两对比,看是否相同,相同的数就把其中一个放回队列,否则就同时舍弃两个,如此循环下去,直到队列中只剩下一个数即为所求。
#include <cstdio>#include <iostream>#include <queue>using namespace std;int main(){int n,num;queue<int> q;while(scanf("%d",&n)!=EOF){for(int i=1;i<=n;i++){scanf("%d",&num);q.push(num);}while(q.size()>1){int a=q.front();q.pop();int b=q.front();q.pop();if(a==b){q.push(a);}}printf("%d\n",q.front());q.pop();}return 0;}法四:网上较好的一个思路
#include <cstdio> #include <iostream>using namespace std;int main(){ int ans,num,count,n; while(scanf("%d",&n)!=EOF){ count=0; for(int i=1;i<=n;i++){ scanf("%d",&ans); if(count==0){ num=ans; count++; } else if(ans==num) count++; else count--; } printf("%d\n",num); } return 0; }
1 0
- hdu 1029 Ignatius and the Princess IV
- HDU 1029 Ignatius and the Princess IV
- HDU 1029 Ignatius and the Princess IV
- HDU 1029 Ignatius and the Princess IV
- hdu 1029 Ignatius and the Princess IV
- hdu 1029 Ignatius and the Princess IV
- hdu 1029 Ignatius and the Princess IV
- hdu 1029 Ignatius and the Princess IV
- Ignatius and the Princess IV hdu 1029
- hdu 1029 Ignatius and the Princess IV
- HDU 1029 Ignatius and the Princess IV
- HDU 1029 Ignatius and the Princess IV
- hdu 1029 Ignatius and the Princess IV
- hdu 1029 Ignatius and the Princess IV
- HDU 1029 Ignatius and the Princess IV
- HDU-1029-Ignatius and the Princess IV
- HDU--1029--Ignatius and the Princess IV
- hdu - 1029 -Ignatius and the Princess IV
- JUC 可重入 读写锁 ReentrantReadWriteLock
- 什么是程序,进程和线程?三者之间有何关系?
- (0)银行新核心项目开工了!!!
- 设计模式——创建型模式之单例模式
- Win10/Win7小技巧:教你如何彻底关闭系统进程
- hdu 1029 Ignatius and the Princess IV
- 1060. Are They Equal (25)
- Red and Black——个人c++解
- 随笔
- Valgrind使用简介
- linux添加头文件路径
- uploadify插件实现多文件上传
- 第一个Java程序
- [python]pip常用命令(转载)