PAT甲题题解-1054. The Dominant Color (20)-排序/map
2017-03-12 15:49
375 查看
原本用map,发现超时了,后来便先用数组存储排个序,最后for一遍统计每种颜色出现的次数(每种颜色的首位索引相减+1),找出最多的即可。
View Code
然而没注意到题目中,说到出现最多的颜色肯定是大于一半区域的,其实用map映射来统计,只要有出现大于一半的直接输出然后break,是不会超时。
#include <iostream> #include <cstdio> #include <algorithm> #include <string.h> #include <map> using namespace std; const int maxn=500000; long long color[maxn]; int main() { int m,n; scanf("%d %d",&m,&n); long long a,ans; int cnt=0; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ scanf("%lld",&a); color[cnt++]=a; } } sort(color,color+cnt); int tmp; int last=0;//每种颜色的第一个索引 int maxcnt=0; ans=color[0]; color[cnt]=-1; for(int i=1;i<=cnt;i++){ if(color[i]!=color[i-1]){ tmp=i-last; if(tmp>maxcnt){ maxcnt=tmp; ans=color[i-1]; } last=i; } } printf("%lld\n",ans); return 0; }
View Code
然而没注意到题目中,说到出现最多的颜色肯定是大于一半区域的,其实用map映射来统计,只要有出现大于一半的直接输出然后break,是不会超时。
相关文章推荐
- PAT - 甲级 - 1054. The Dominant Color (20)(STL-map)
- PAT 1054. The Dominant Color (20)(简单排序题(`vector<int>`利用`map<int,int>`来排序))
- 1054. The Dominant Color (20)【水题】——PAT (Advanced Level) Practise
- 1054. The Dominant Color (20)-PAT
- PAT (Advanced) 1054. The Dominant Color (20)
- PAT: 1054. The Dominant Color (20)
- 浙江大学PAT_甲级_1054. The Dominant Color (20)
- PAT 1054. The Dominant Color (20)
- PAT 1054. The Dominant Color (20) 找序列中某个元素出现一半以上;
- 【PAT】【Advanced Level】1054. The Dominant Color (20)
- PAT1054. The Dominant Color (20)
- PAT-A1054. The Dominant Color 【STL-map】
- PAT_A 1054. The Dominant Color (20)
- PAT 1054. The Dominant Color (20)
- PAT 1054. The Dominant Color (20)
- 【PAT甲级】1054. The Dominant Color (20)
- PAT (Advanced Level) Practise 1054 The Dominant Color (20)
- PAT-A-1054. The Dominant Color (20)
- PAT 1054. The Dominant Color (20)
- PAT 1054. The Dominant Color (20)