SGU 180 Inversions

来源:互联网 发布:凸优化理论与应用 编辑:程序博客网 时间:2024/05/21 21:42

题意就是求 逆序数。

依然线段树水过。

→_→ 模版题。这下严格注意各种坑。1A。


#include<cstdio>#include<cstring>#include<string>#include<queue>#include<algorithm>#include<map>#include<stack>#include<iostream>#include<list>#include<set>#include<bitset>#include<vector>#include<cmath>#define INF 0x7fffffff#define eps 1e-8#define LL long long#define PI 3.141592654#define CLR(a,b) memset(a,b,sizeof(a))#define FOR(i,a,b) for(int i=a;i<b;i++)#define FOR_(i,a,b) for(int i=a;i>=b;i--)#define sf scanf#define pf printf#define all(v) (v).begin(),(v).end()#define acfun std::ios::sync_with_stdio(false)#define SIZE (65537  +2)#define MOD 1000000007using namespace std;struct node{    int val,pos;    bool friend operator <(node a,node b)    {        if(a.val==b.val)            return a.pos>b.pos;        return a.val>b.val;    }}l[SIZE];int t[SIZE*4];int up;void update(int o,int l,int r){    if(l==r)t[o]=1;    else    {        int m=(l+r)>>1;        if(up<=m)update(o*2,l,m);        else update(o*2+1,m+1,r);        t[o]=t[o*2]+t[o*2+1];    }}int ql,qr;int query(int o,int l,int r){    if(l>=ql&&r<=qr)return t[o];    int m=(l+r)>>1;    int ans=0;    if(ql<=m)ans+=query(o*2,l,m);    if(qr>m)ans+=query(o*2+1,m+1,r);    return ans;}int main(){    int n;    while(sf("%d",&n)!=EOF)    {        FOR(i,1,n+1)        {            sf("%d",&l[i].val);            l[i].pos=i;        }        sort(l+1,l+1+n);        CLR(t,0);        LL ans=0;        FOR(i,1,n+1)        {            up=l[i].pos;            update(1,1,n);            ql=1,qr=up-1;            if(ql<=qr)            ans+=query(1,1,n);        }        pf("%lld\n",ans);    }}


0 0
原创粉丝点击