题目链接:http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=95
常规方法:遍历查找+小小优化(排序)
常规方法AC代码:
#include<cstdio>
#include<algorithm>
using namespace std;
bool cmp(int a,int b)
{
return a<b;
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
int m,i,j,total_now=0,total_last=0,most_now,most_last;
scanf("%d",&m);
int *p=new int [m+5];
for(i=0;i<m;i++)
{
scanf("%d",&p[i]);
}
sort(p,p+m,cmp);
most_last=most_now=p[0];
for(i=0;i<m;i++)
{
most_now=p[i];
total_now=0;
for(j=i;j<m;j++)
{
if(p[i]==p[j])
{
total_now++;
if(total_now>total_last)
{
total_last=total_now;
most_last=most_now;
}
}
else
{
i=j-1;
break;
}
}
}
printf("%d %d\n",most_last,total_last);
}
return 0;
}
STL之map,pair
因为正在学习STL,所以参考了多篇博文,若干源码
oj上给出的源码使用了pair容器,关于pair容器,可查阅:http://blog.youkuaiyun.com/return___0/article/details/79244992
关于map容器,可查阅:http://blog.youkuaiyun.com/return___0/article/details/79245302
http://www.cnblogs.com/empty16/p/6395813.html
个人理解:map相当于是pair的数组形式?
源码中还使用了max_element,其含义及来源为
min_element()和max_element
头文件:#include<algorithm>
作用:返回容器中最小值/最大值。max_element(first,end,cmp);其中cmp为可选择参数!与sort排序中cmp意义相仿
以下是标程:
#include<iostream>
#include<cmath>
#include<map>
#include<algorithm>
using namespace std;
bool myless(pair<int,int> p1,pair<int,int> p2)
{
return p1.second<p2.second;
}
int main()
{
int n;
cin>>n;
while(n--)
{
int w,a;
map<int,int> mp;
cin>>w;
while(w--)
{
cin>>a;
++mp[a];
}
map<int,int>::iterator it=max_element(mp.begin(),mp.end(),myless);
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
其中:
++mp[a];
我的理解是map容器mp中键为a的值自增如不容易理解,可参阅另一位作者的简化版map:
#include<iostream>
#include<map>
using namespace std;
int main()
{
int n;
cin>>n;
while(n--)
{
int m,num;
map<int,int>s;
cin>>m;
int t=0;
int ans=0;
for(int i=0;i<m;i++)
{
cin>>num;
s[num]++;
if(s[num]>ans)
{
t=num;
ans=s[num];
}
}
cout<<t<<' '<<ans<<endl;
}
return 0;
}