Total Submit: 116 Accepted Submit: 24
|
Algorithm:
直接计算的复杂度是O(N^2),不可取。应先对点按x大小排序,然后分治,对点按y大小归并排序,同时统计。
下面是我的代码:
//by Sun Hong; May 4th,2005
//Algorithm--Divide and Conquer,complexity--O(N*logN)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const int maxn=50000;
typedef struct
{
int x,y;
}Tpoint;
Tpoint p[maxn],tp[maxn];
int N,ans;
int cmp_x(const void *t1,const void *t2)
{
Tpoint *a,*b;
a=(Tpoint*)t1; b=(Tpoint*)t2;
return a->x-b->x;
}
void swap(Tpoint &a,Tpoint &b)
{
Tpoint temp;
temp=a; a=b; b=temp;
}
void MergeSort(int left,int right)
{
int mid,i,j,k;
mid=(left+right)/2;
if (right-left<=1)
{
if (p[left].y>p[right].y)
{
ans++; swap(p[left],p[right]);
}
return;
}
MergeSort(left,mid); MergeSort(mid+1,right);
i=mid; j=right; k=right-left;
while (i>=left && j>mid)
{
if (p[i].y>p[j].y){
ans+=j-mid; tp[k--]=p[i--];
}else
tp[k--]=p[j--];
}
while (i>=left) tp[k--]=p[i--];
while (j>mid) tp[k--]=p[j--];
memcpy(p+left,tp,(right-left+1)*sizeof(Tpoint));
}
int main()
{
int i;
//freopen("points.in","r",stdin);
//freopen("points.out","w",stdout);
while (1==scanf("%d",&N))
{
for (i=0;i<N;i++) scanf("%d%d",&p[i].x,&p[i].y);
qsort(p,N,sizeof(Tpoint),cmp_x);
ans=0;
MergeSort(0,N-1);
printf("%d/n",ans);
}
return 0;
}