paper plane fly away

链接: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;
}
  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值