Description
x轴上一些点x[i]处有一个p[i]个人的城市,对于每个城市定义其父亲城市为离其最近的人数比其多的城市,如果有两个城市距其距离相同且都是最近的,那么人数多的那个城市是其父亲城市,求每个城市的父亲城市
Input
第一行一整数n表示城市数量,之后n行每行两个整数x[i]和p[i]表示第i个城市在x[i]处且人口为p[i],p[i]互不相同
(1<=n<=2e5,1<=x[i],p[i]<=1e9)
Output
输出n个整数表示每个城市的父亲城市,没有则输出-1
Sample Input
4
1 1000
7 10
9 1
12 100
Sample Output
-1 4 2 1
Solution
按人数降序排,从大到小把城市插入到set里,这样当插入第i个城市之前,set里存的是所有人数大于pi]的城市,二分搜索找到距离离其最近的城市(0个或1个或2个),0个则该城市没有父亲城市,一个那么这个就是其父亲城市,两个就比一下人数,多的那个是其父亲城市
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
#define INF 0x3f3f3f3f
#define maxn 222222
typedef pair<int,int>P;
set<P>s1;
set<P>::iterator pre,next;
int n;
struct node
{
int x,p,id;
bool operator<(const node&b)const
{
return p>b.p;
}
}a[maxn];
int ans[maxn];
map<int,int>M;
int main()
{
while(~scanf("%d",&n))
{
M.clear(),s1.clear();
for(int i=1;i<=n;i++)
{
scanf("%d%d",&a[i].x,&a[i].p);
a[i].id=i;
M[a[i].x]=i;
}
sort(a+1,a+n+1);
for(int i=1;i<=n;i++)
{
int x=a[i].x,id=a[i].id;
ans[id]=-1;
pre=next=s1.lower_bound(P(x,-1));
if(s1.size()>0)
{
if(next==s1.end())pre--,ans[id]=(*pre).first;
else
{
if(next==s1.begin())ans[id]=(*next).first;
else
{
pre--;
int d1=x-(*pre).first,d2=(*next).first-x,p1=(*pre).second,p2=(*next).second;
if(d1<d2||d1==d2&&p1<p2)ans[id]=(*pre).first;
else ans[id]=(*next).first;
}
}
}
s1.insert(P(x,i));
}
for(int i=1;i<=n;i++)
{
if(ans[i]==-1)printf("-1");
else printf("%d",M[ans[i]]);
printf("%c",i==n?'\n':' ');
}
}
return 0;
}