链接:https://ac.nowcoder.com/acm/contest/903/E
来源:牛客网
There are n boys, indexed from 1 to n, and n girls indexed from n+1 to 2n.
One day, they have a party together. The girls are seated in the first row, and the boys sit in the second row. They take their seat in such a way, that a boy sit just behind a girl, and boy indexed 1 sit on the leftmost chair, 2 sit on the second, etc.
Each boy has a girl he likes,and he may make contact to his sweetheart, by writing down what he wants to tell her on a piece of paper, and makes it a paper plane, which he will throw directly at her. You may assume that the plane will go in a straight line.
But, the trouble occurs, when two paper plane collide in the air and drop halfway. Obviously, this will be extremely awkward. So each boy wants to know, if he throws his paper plane, how many paper planes have the potential to collide with it halfway.
It’s guaranteed that each girl is the sweetheart of exactly one boy.
输入描述:
The first line contains a single integer n.
Then n lines follow, the i-th of which contains two integers, the index of the girl seated in front of the i-th boy and the girl he likes.
1
≤
n
≤
10
5
1≤n≤105
输出描述:
Output n lines, the i-th of which contains one integer, the number of planes that may collide with i-th boy’s plane.
示例1
输入
复制
5
7 9
6 6
8 10
9 7
10 8
输出
复制
3
2
2
3
2
这个题,我在场时的思路是把喜欢的人的连用图来存起来,然后之后没飞一个飞机就行和列去扫描,,,,思路比较清晰,但是实在是太慢了
以下是题解:
用树状数组做,快速求得前i项和,正反插入两次,求得逆序对的数量和
参考了一位大佬写的代码
#include<bits/stdc++.h>
using namespace std;
const int MAX = 1e6+5;
int n,a[MAX],b[MAX],c[MAX],l[MAX],count1[MAX],count2[MAX];
int lowbit(int x){
return x&(-x);
}
int sum(int x){
int ans=0;
for(;x>0;x-=lowbit(x)) ans+=c[x];
return ans;
}
void add(int x,int count){
for(;x<=n;x+=lowbit(x)) c[x]+=count;
}
void solve(){
scanf("%d",&n);
for(int i=1;i<=n;++i){
int num1,num2;
scanf("%d%d",&num1,&num2);
a[i]=num2,b[num1]=i;
}
for(int i=1;i<=n;++i) l[i]=b[a[i]];
memset(c,0,sizeof(c));
for(int i=1;i<=n;++i){
count1[i]=sum(n)-sum(l[i]);
add(l[i],1);
}
memset(c,0,sizeof(c));
for(int i=n;i>=1;--i){
count2[i]=sum(l[i]-1);
add(l[i],1);
}
for(int i=1;i<=n;++i) printf("%d\n",count1[i]+count2[i]);
}
int main(void)
{
solve();
return 0;
}