求逆序对

树状数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
struct node{int id,sum;}a[maxn];
int n,ans,c[maxn],x[maxn];
bool comp(node x,node y){return x.sum<y.sum;}
int lowbit(int x){return x&(-x);}
void add(int x){for(int i=x;i<=n;i+=lowbit(i))c[i]++;}
int getsum(int x)
{
int sum=0;
for(int i=x;i;i-=lowbit(i))
sum=(sum+c[i]);
return sum;
}
int main()
{
scanf("%d",&n);
for(int i=1;i<=n;++i)scanf("%d",&a[i].sum),a[i].id=i;
sort(a+1,a+1+n,comp);
for(int i=1;i<=n;++i)x[a[i].id]=i;
for(int i=n;i>=1;--i)
{
add(x[i]);
ans=(ans+getsum(x[i]-1));
}
printf("%d",ans);
return 0;
}

归并排序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<queue>
#include<vector>
#include<algorithm>
#include<cmath>
#include<stack>
#include<map>
using namespace std;
#define R register
#define ll long long
#define fo(i,a,b) for(R int (i)=(a);(i)<=(b);++(i))
#define debug(x) cout<<#x<<"="<<x<<endl
int n,a[maxn],tmp[maxn],ans=0;
void mer(int l,int r)
{
if(l==r)return;
R int mid=(l+r)>>1;
mer(l,mid);
mer(mid+1,r);
R int i=l,j=mid+1,p=l;
while(i<=mid&&j<=r)
{
if(a[i]<=a[j])tmp[p++]=a[i++];
else tmp[p++]=a[j++],ans+=mid-i+1;
}
while(i<=mid)tmp[p++]=a[i++];
while(j<=r)tmp[p++]=a[j++];
fo(i,l,r)a[i]=tmp[i];
}
int main()
{
scanf("%d",&n);
fo(i,1,n)scanf("%d",&a[i]);
mer(1,1<<n);
cout<<ans;
return 0;
}

显示 Gitment 评论