这道题看完之后,感觉没别的招,得排序找最小值,但是如果这么做,指定TLE,
所以可以用map容器,map里的第一个参数是关键字,第二个是关键值,map的内部是由一颗非严格意义上的红黑树组成的,所以map内部是有序的,默认是从mp.begin()开始到mp.end()结束从小到大排序,所以省去了排序的时间,这道题AC 250ms感觉还是挺有效率的~~~
#include <iostream>
#include <cstdio>
#include <string.h>
#include <map>
using namespace std;
int main()
{
int n;
while(cin>>n&&n)
{
map<int,int>mp;
mp[1000000000]=1; //先初始化
for(int i=0;i<n;i++)
{
int a,b;
scanf("%d%d",&a,&b);
map<int,int>::iterator it;
it=mp.lower_bound(b); //返回的是b的下界(迭代器)里面的内容是大于等于b的;
if(it==mp.begin())
printf("%d %d\n",a,it->second); //边插入边输出。。。
else
{
map<int,int>::iterator k1=it,k2=--it;
if((k1->first)-b>=b-(k2->first))
printf("%d %d\n",a,k2->second);
else
printf("%d %d\n",a,k1->second);
}
mp[b]=a;
}
}
return 0;
}