Gym - 100971D Laying Cables【单调栈】
One-dimensional country has n cities, the i-th of which is located at the point xi and has population pi, and all xi, as well as all pi, are distinct. When one-dimensional country got the Internet, it was decided to place the main server in the largest city, and to connect any other city j to the city k that has bigger population than j and is the closest to it (if there are many such cities, the largest one should be chosen). City k is called a parent of city j in this case.
Unfortunately, the Ministry of Communications got stuck in determining from where and to where the Internet cables should be laid, and the population of the country is suffering. So you should solve the problem. For every city, find its parent city.
Input
The first line contains a single integer n (1 ≤ n ≤ 200000) — the number of cities.
Each of the next n lines contains two space-separated integers xi and pi (1 ≤ xi, pi ≤ 109) — the coordinate and the population of the i-th city.
Output
Output n space-separated integers. The i-th number should be the parent of the i-th city, or - 1, if the i-th city doesn’t have a parent. The cities are numbered from 1 by their order in the input.
Examples
Input
4
1 1000
7 10
9 1
12 100
Output
-1 4 2 1
Input
3
1 100
2 1
3 10
Output
-1 1 1
Input
3
1 10
3 100
2 1
Output
2 -1 2
题意:
今年村里刚通网,有很多个城市在一个一维坐标上,每个城市有坐标和人口数(城市大小)
现在连网线,大的往小的连,即大的是小的父亲,输出每个城市的父亲
连线条件:
对于被连接的儿子,他的父亲是离他最近的且比他大的,若有两个一样近,则更大的是他父亲
数据保证没有相同坐标,没有相同大小
解:
- 维护一个单调栈:栈顶最小,栈底最大
- 先把每个城市从左到右排好(排序的时候每个城市要记住自己原来在哪,因为答案要按照原来的顺序输出)
- 从左往右放入单调栈,(把不符合条件的弹掉)栈顶元素则为离当前元素最近的且比它大的,将父亲设为栈顶元素
- 然后从右往左再来一遍,这时有的元素已经有父亲了,则比较这两个父亲谁好,留一个
- 然后再按原来的顺序排回去,输出答案
代码解释:
创建结构体node
创建Mystack类继承stack< node >并重写push(),新建了clear()用于清空栈
数组p[i]表示从左往右数的第i个元素的父亲是从左往右数的第几个
1 |
|