Qiuqiqiu  
不管道路多么崎岖坎坷,我永远不停下追逐梦想的脚步!

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3574

求逆序对

归并排序O(nlogn),《算法竞赛入门经典》P144

View Code
 1 //zoj 3574
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 const int N=30100;
6 struct yy
7 {
8 int l,r;
9 }y[N];
10 int a[N],b[N];
11 int cmp(const void *a,const void *b)
12 {
13 return ((yy*)a)->l - ((yy*)b)->l;
14 }
15 void msort(int l,int r,int &cnt)
16 {
17 if (l==r) return;
18 int m=(l+r)/2;
19 msort(l,m,cnt);
20 msort(m+1,r,cnt);
21 int p=l,q=m+1,i=l;
22 while (p<=m || q<=r)
23 {
24 if (q>r || (p<=m && a[p]<=a[q])) b[i++]=a[p++];
25 else {b[i++]=a[q++]; cnt+=m-p+1;}
26 }
27 for (i=l;i<=r;i++) a[i]=b[i];
28 }
29 int main()
30 {
31 int lx,rx,n,i;
32 while (~scanf("%d%d%d",&lx,&rx,&n))
33 {
34 int k,b;
35 for (i=1;i<=n;i++)
36 {
37 scanf("%d%d",&k,&b);
38 y[i].l=k*lx+b;
39 y[i].r=k*rx+b;
40 }
41 qsort(y+1,n,sizeof(y[0]),cmp);
42 for (i=1;i<=n;i++) a[i]=y[i].r;
43 int cnt=0;
44 msort(1,n,cnt);
45 printf("%d\n",n+cnt+1);
46 }
47 return 0;
48 }

 

posted on 2012-02-27 08:06  Qiuqiqiu  阅读(245)  评论(0编辑  收藏  举报