网上买的真题,答案少满足了两个条件:
1. 没有考虑p1 < p2;
2. 没有考虑p1相等时,p2升序的情况。
以下是我写的代码:
/*
输入:
5
1 90
2 91
3 89
4 85
5 86
输入:
4
1 90
2 91
3 100
4 89
*/
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
bool cmp1(pair<int, int> a, pair<int, int> b)
{
return a.second <= b.second;
}
bool cmp(pair<int, int> a, pair<int, int> b)
{
if (a.first = b.first)
{
return a.second <= b.second;
}
else
{
return a.first < b.first;
}
// return a.first < b.first;
}
int main()
{
int n;
cin >> n;
int n_temp = n;
vector<pair<int, int>> input_vec;
while (n_temp--)
{
pair<int, int> my_pair;
cin >> my_pair.first >> my_pair.second;
input_vec.push_back(my_pair);
}
sort(input_vec.begin(), input_vec.end(), cmp1);
// 找分差最小的
int pre_fencha = 301; // 最大分差为300
vector<pair<int, int>> fencha_vec;
for (int i = 0; i < n - 1; i++)
{
int cur_fencha = input_vec[i + 1].second - input_vec[i].second;
if (cur_fencha == pre_fencha)
{
fencha_vec.push_back({input_vec[i + 1].first, input_vec[i].first});
}
else if (cur_fencha < pre_fencha)
{
fencha_vec.clear();
fencha_vec.push_back({input_vec[i + 1].first, input_vec[i].first});
pre_fencha = cur_fencha;
}
else
{
cur_fencha = cur_fencha;
}
}
vector<pair<int, int>> result;
for (pair<int, int> my_pair : fencha_vec)
{
// 错误:pair不能更改first和second的值
// if (pair.first > pair.second)
// {
// int temp = pair.second;
// pair.second = pair.first;
// pair.first = temp;
// }
if (my_pair.first > my_pair.second)
{
pair<int, int> my_pair_1(my_pair.second, my_pair.first);
result.push_back(my_pair_1);
continue;
}
result.push_back(my_pair);
}
// 排序
sort(result.begin(), result.end(), cmp);
for (auto pair : result)
{
cout << pair.first << " " << pair.second << endl;
}
}