Shaolin(map)

时间:2022-07-28
本文章向大家介绍Shaolin(map),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题意描述

Shaolin temple is very famous for its Kongfu monks.A lot of young men go to Shaolin temple every year, trying to be a monk there. The master of Shaolin evaluates a young man mainly by his talent on understanding the Buddism scripture, but fighting skill is also taken into account. When a young man passes all the tests and is declared a new monk of Shaolin, there will be a fight , as a part of the welcome party. Every monk has an unique id and a unique fighting grade, which are all integers. The new monk must fight with a old monk whose fighting grade is closest to his fighting grade. If there are two old monks satisfying that condition, the new monk will take the one whose fighting grade is less than his. The master is the first monk in Shaolin, his id is 1,and his fighting grade is 1,000,000,000.He just lost the fighting records. But he still remembers who joined Shaolin earlier, who joined later. Please recover the fighting records for him.

依次给出和尚序列,寻找与自己的战力相差最小的和尚,输出战斗的顺序

思路

由于之前只是简单学了map的使用,对于map的遍历没有研究过。这道题也是现学现做的。由于id和战力的唯一性,所以我们可以使用map来进行映射,由于map是有序的,所以map对应的映射可以为[战力:id],然后每次输入后利用lower_bound来寻找最接近的,然后比较即可。

AC代码

#include<bits/stdc++.h>
#define x first
#define y second
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=1e5+10;
const int M=150;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
void solve(){
    int n;
    while(cin>>n && n){
        vector<PII> ans;
        map<int,int> mp;
        map<int,int>::iterator it1,it2,it3;
        mp[1000000000]=1;
        for(int i=0;i<n;i++){
            int idx,power;cin>>idx>>power;
            it1=mp.lower_bound(power);
            if(it1==mp.begin()){
                ans.push_back({idx,it1->second});
            }else{
                it2=it1;
                it3=--it1;
                if(abs(it2->first-power)>=abs(it3->first-power)){
                    ans.push_back({idx,it3->second});
                }else ans.push_back({idx,it2->second});
            }
            mp[power]=idx;
        }
        for(int i=0;i<ans.size();i++) cout<<ans[i].x<<' '<<ans[i].y<<endl;
    }
}
int main(){
    IOS;
    solve();
    return 0;
}