hdu 1029 Ignatius and the Princess IV(水题,map)
来源:互联网 发布:java培训机构学费 编辑:程序博客网 时间:2024/06/02 01:58
小记:细节决定成败。 最近又被朋友问及到这样一道题,说如果大数据,如何O(n)实现。实在没想通
思路:题目没说给定的数可能有多大,如果是long long型,就不能用数组来叠加了。这里选择用map将long long 映射到int,进行计数。
因为对于n=2这个是一个特殊情况。我们必须输出这两个数,它们都是special number。
代码:
#include <iostream>#include <cstdio>#include <map>using namespace std;map<long long, int>mp;map<long long, int>::iterator q;int main(){ long long n,m, ans, T; bool flag; while(cin>>n){ mp.clear(); flag = 0;T = n; while(n--){ cin>>m; mp[m]++; if(mp[m] == (T+1)/2){ if(flag)cout<<" ";flag=1;cout<<m;} } cout<<endl; } return 0;}
#include <iostream>#include <cstdio>#include <map>using namespace std;const int MAX_ = 130;int p[MAX_];map<long long, int>mp;map<long long, int>::iterator q;int main(){ //freopen("f:\\out.txt","w",stdout); long long n,m, ans, T; while(cin>>n){ mp.clear(); ans = 0;T = n; while(n--){ cin>>m; mp[m]++; if(mp[m] == (T+1)/2){ p[ans++] = m; } } cout<<p[0]; for(int i = 1; i < ans; ++i) cout<<" "<<p[i]; cout<<endl; } return 0;}
我们从头一个数一个数的判断,如果某一个数是最多的那个数,那么去掉这个数后剩下的数中,这个数还会是最多的,
我们利用抵消原理,如果碰上两个不相同的数,那么我们就要抵消掉一个,
假设从第一个开始,用cnt来计数,res表示计数的数,当当前的数等于res时,cnt++
不等于时,cnt--,
而若cnt=0的时候,那么说明res这个数肯定就不是最多的那个数,此时我们再将res和cnt初始化为当前的数,即res等于当前的数,cnt=1
这个想法简直是太棒了!
#include <iostream>#include <stdio.h>#include <string.h>#include <math.h>#include <stdlib.h>#include <map>#include <set>#include <vector>#include <stack>#include <algorithm>using namespace std;#define mst(a,b) memset(a,b,sizeof(a))#define eps 10e-8const int MAX_ = 1000010;const int N = 100010;const int INF = 0x7fffffff;int main(){int n, cnt, k, res;while(~scanf("%d",&n)){ cnt = 0; while(n--){ scanf("%d",&k); if(cnt == 0)res = k,cnt = 1; else { if(k == res)cnt++; else cnt --; } } printf("%d\n",res);}return 0;}
0 0
- hdu 1029 Ignatius and the Princess IV(水题,map)
- hdu 1029 Ignatius and the Princess IV(水题)
- HDU 1029 Ignatius and the Princess IV(水题)
- hdu 1029 Ignatius and the Princess IV //map的使用
- HDU--1029 Ignatius and the Princess IV (map&&思维&&memset)
- Ignatius and the Princess IV(map)
- 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
- VB.NET概述
- IOS CGAffineTransform 用于视图平移,放缩,旋转
- Linux设备驱动程序学习(7)-内核的数据类型(深入分析Linux内核链表)
- ubuntu系统下虚拟打印机问题
- linux配置网卡
- hdu 1029 Ignatius and the Princess IV(水题,map)
- kafka测试
- 玩转Web之easyui(三)-----easy ui dataGird 重新指定url以获取不同数据源信息
- android:descendantFocusability用法简析
- HHVM 是如何提升 PHP 性能的?
- 目标检测的图像特征提取 HOG特征
- 实现BFS之“营救”
- linux快速搭建vsftpd服务以及常见问题
- Linux设备驱动程序学习(4)-高级字符驱动程序操作[(1)ioctl and llseek]