nyoj 众数问题 STL--map,pair

本文介绍了一种使用STL中的map容器来高效解决众数查找问题的方法,并对比了传统遍历查找加排序的方法。通过示例代码详细解释了如何利用map容器统计元素出现频率并找出众数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: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; 
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值