POJ
P2299:显然逆序对,树状、线段树、归并随意
Pascal与C++速度差异很大,目测基本一样,但一个超时,一个500MS 求神犇指导(树状)
1 #include <iostream> 2 #include <cstring> 3 #include <cstdio> 4 #include <algorithm> 5 using namespace std; 6 7 const int N = 500005; 8 9 struct Node 10 { 11 int val; 12 int pos; 13 }; 14 15 Node node[N]; 16 int c[N], reflect[N], n; 17 18 bool cmp(const Node& a, const Node& b) 19 { 20 return a.val < b.val; 21 } 22 23 int lowbit(int x) 24 { 25 return x & (-x); 26 } 27 28 void update(int x) 29 { 30 while (x <= n) 31 { 32 c[x] += 1; 33 x += lowbit(x); 34 } 35 } 36 37 int getsum(int x) 38 { 39 int sum = 0; 40 while (x > 0) 41 { 42 sum += c[x]; 43 x -= lowbit(x); 44 } 45 return sum; 46 } 47 48 int main() 49 { 50 while (scanf("%d", &n) != EOF && n) 51 { 52 for (int i = 1; i <= n; ++i) 53 { 54 scanf("%d", &node[i].val); 55 node[i].pos = i; 56 } 57 sort(node + 1, node + n + 1, cmp); //排序 58 for (int i = 1; i <= n; ++i) reflect[node[i].pos] = i; //离散化 59 for (int i = 1; i <= n; ++i) c[i] = 0; //初始化树状数组 60 long long ans = 0; 61 for (int i = 1; i <= n; ++i) 62 { 63 update(reflect[i]); 64 ans += i - getsum(reflect[i]); 65 } 66 printf("%lld\n", ans); 67 } 68 return 0; 69 }
1 program poj; 2 type 3 node=record 4 v,p:longint; 5 end; 6 var 7 n,i,j:longint; 8 ans:int64; 9 c:array [0..500001] of longint; 10 a:array [0..500001] of node; 11 r:array [0..500001] of longint; 12 procedure qsort(l,r:longint); 13 var 14 mid,i,j:longint; 15 t:node; 16 begin 17 i:=l;j:=r;mid:=a[random(l+(r-l+1))].v; 18 repeat 19 while (a[i].v<mid) do inc(i); 20 while (mid<a[j].v) do dec(j); 21 if i<=j then begin 22 t:=a[i];a[i]:=a[j];a[j]:=t; 23 inc(i);dec(j); 24 end; 25 until i>j; 26 if i<r then qsort(i,r); 27 if l<j then qsort(l,j); 28 end; 29 function bit(x:longint):longint; 30 begin 31 exit(x and (-x)); 32 end; 33 procedure change(x:longint); 34 begin 35 while x<=n do begin 36 inc(c[x]); 37 inc(x,bit(x)); 38 end; 39 end; 40 function ask(x:longint):longint; 41 var 42 sum:longint; 43 begin 44 sum:=0; 45 while x>0 do begin 46 inc(sum,c[x]); 47 dec(x,bit(x)); 48 end; 49 exit(sum); 50 end; 51 begin 52 randomize; 53 readln(n); 54 while n>0 do begin 55 for i:=1 to n do 56 with a[i] do begin 57 readln(v);p:=i; 58 end; 59 qsort(1,n); 60 for i:=1 to n do c[i]:=0; 61 ans:=0; 62 for i:=1 to n do r[a[i].p]:=i; 63 for i:=1 to n do begin 64 change(r[i]); 65 inc(ans,i-ask(r[i])); 66 end; 67 writeln(ans); 68 readln(n); 69 end; 70 end.