map,max_element仿函数的写法

本文提供了一道典型的C++编程题解答示例,通过使用STL中的map和自定义比较器来找出出现次数最多的整数及其频次。适用于算法竞赛训练。

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

一道很典型的题目,本文章仅作备忘使用。

http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2521

#include <iostream>
#include <map>
#include <algorithm>

using namespace std;

class comp
{
public:
	bool operator () (const pair< int, int > &a, const pair < int, int > &b)
	{
		return  a.second == b.second ? a.first > b.first : a.second < b.second; 
	}
};

int main()
{
	int n;
	while(cin>>n)
	{
		map<int, int> a;
		while(n--)
		{
			int num;
			cin>>num;
			++a[num];
		}
		map<int,int>::iterator it_max = max_element(a.begin(),a.end(),comp());
		cout<<it_max->first<<' '<<it_max->second<<endl;
	}
}


改为c++14 #include <iostream> #include <vector> #include <unordered_map> #include <algorithm> // 用于max_element/min_element #include <climits> // 用于INT_MIN/INT_MAX using namespace std; struct PositionData { int count = 0; int first = INT_MAX; int last = INT_MIN; vector<int> positions; }; int main() { // 读取输入 int n; cin >> n; vector<int> a(n); for (int i = 0; i < n; ++i) { cin >> a[i]; } // 创建数据结构 unordered_map<int, PositionData> data; // 遍历数组填充数据 for (int idx = 0; idx < n; ++idx) { int num = a[idx]; auto& d = data[num]; // 自动创建新条目 d.count++; d.first = min(d.first, idx); d.last = max(d.last, idx); d.positions.push_back(idx); } // 计算sum_max和x_list int sum_max = 0; vector<int> x_list; for (const auto& [num, info] : data) { sum_max += min(info.count, 3); if (info.count >= 3) { x_list.push_back(num); } } // 处理无x的情况 if (x_list.empty()) { cout << sum_max << endl; return 0; } // 计算L和R int L = INT_MIN; int R = INT_MAX; for (int x : x_list) { L = max(L, data[x].first); R = min(R, data[x].last); } // 处理无重叠情况 if (L >= R) { sum_max -= x_list.size(); cout << sum_max << endl; return 0; } // 二分查找处理 int t = 0; for (int x : x_list) { const auto& pos = data[x].positions; int left = 0, right = pos.size() - 1; bool found = false; while (left <= right) { int mid = (left + right) / 2; if (pos[mid] > L && pos[mid] < R) { found = true; break; } else if (pos[mid] <= L) { left = mid + 1; } else { right = mid - 1; } } if (!found) { t++; } } // 最终结果 sum_max -= t; cout << sum_max << endl; return 0; }
03-16
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值