逆序对数的应用;
逆序对数的写法有,二分,树状数组,分治;
学习一下;
树状数组版:
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=;
int a[maxn],b[maxn],c[maxn];
int n;
struct point
{
int num,index;
bool operator<(const point& t)const
{
return num<t.num;
}
}p[maxn]; int lowbit(int x)
{
return x&(-x);
} void updata(int i,int x)
{
while(i<=n)
{
c[i]+=x;
i=i+lowbit(i);
}
} int sum(int x)
{
int ans=;
while(x>)
{
ans+=c[x];
x-=lowbit(x);
}
return ans;
} int main()
{
int i,j;
while(scanf("%d",&n)!=EOF)
{
memset(c,,sizeof c);
for(i=;i<=n;i++)
{
scanf("%d",&p[i].num);
p[i].index=i;
}
sort(p+,p+n+);
for(i=;i<=n;i++)
b[p[i].index]=i;
int ans1=,ans2=;
for(i=;i<=n;i++)
{
updata(b[i],);
ans1=ans1+(sum(n)-sum(b[i]));
}
memset(c,,sizeof c);
memset(b,,sizeof b);
for(i=;i<=n;i++)
{
scanf("%d",&p[i].num);
p[i].index=i;
}
sort(p+,p+n+);
for(i=;i<=n;i++)
b[p[i].index]=i;
for(i=;i<=n;i++)
{
updata(b[i],);
ans2=ans2+(sum(n)-sum(b[i]));
}
if(ans1%==ans2%) printf("Possible\n");
else printf("Impossible\n");
}
return ;
}
分治版:
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=;
int b[maxn],c[maxn];
int n,cnt;
struct point
{
int num,index;
bool operator<(const point& t)const
{
return num<t.num;
}
}p[maxn]; void merge_sort(int *a,int x,int y,int *t)
{
if(y-x>)
{
int m=(y+x)/;
int p=x,q=m,i=x;
merge_sort(a,x,m,t);
merge_sort(a,m,y,t);
while(p<m||q<y)
{
if(q>=y||(p<m&&a[p]<=a[q])) t[i++]=a[p++];
else
{
t[i++]=a[q++];
cnt+=m-p;
}
}
for(int i=x; i<y; i++)a[i]=t[i];
}
}
int main()
{
int i,j;
while(scanf("%d",&n)!=EOF)
{
for(i=;i<=n;i++)
{
scanf("%d",&p[i].num);
p[i].index=i;
}
sort(p+,p+n+);
for(i=;i<=n;i++)
b[p[i].index]=i;
cnt=;
merge_sort(b,,n+,c);
int ans1=cnt; cnt=;
for(i=;i<=n;i++)
{
scanf("%d",&p[i].num);
p[i].index=i;
}
sort(p+,p+n+);
for(i=;i<=n;i++)
b[p[i].index]=i;
merge_sort(b,,n+,c);
int ans2=cnt;
if(ans1%==ans2%) printf("Possible\n");
else printf("Impossible\n");
}
return ;
}
线段树版的话就不写了,麻烦!