【HDU4585 Shaolin】map的经典运用

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4585

题意大意:很多人想进少林寺,少林寺最开始只有一个和尚,每个人有有一个武力值,若这个人想进少林,必须和比他先进去的人比武并且武力值最接近他的比武,如果有相同的则选择武力值比他小的,问当他进去的时候要和哪个和尚比武。

思路:正常情况暴力,n=100000,呵呵。

        n*n的操作肯定不行的,最少要优化到nlogn,联想到map,map里的数会自动排序,它是由红黑树实现的,能实现O(n)的排序(对第一关键字排序),

        然后再由mp.lower_bound(val)实现logn的查找。

       总算法复杂度 n*logn,map碉堡了。 

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <algorithm>
 4 #include <map>
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     int n, id, p;
10     while(cin >> n,n)
11     {
12         map<int,int>mp;
13         mp[1000000000]=1;
14         for(int i=1; i<=n; i++)
15         {
16             scanf("%d%d",&id,&p);
17             map<int,int>::iterator it=mp.lower_bound(p);
18             if(it==mp.begin()) cout << id << " " << it->second <<endl;
19             else
20             {
21                 map<int,int>::iterator a=it, b=--it;
22                 if((a->first)-p>=p-(b->first))cout << id << " " << b->second <<endl;
23                 else cout << id << " " << a->second <<endl;
24             }
25             mp[p]=id;
26         }
27     }
28     return 0;
29 }
View Code
原文地址:https://www.cnblogs.com/kane0526/p/3256817.html