1691: [Usaco2007 Dec]挑剔的美食家
1 var 2 nnn,root,xx,nn,n,m,i,j:longint;ans:int64; 3 l,r,size,a,an,bn,am,bm:array[1..100000]of longint; 4 function new(x:longint):longint; 5 begin 6 inc(nn); 7 size[nn]:=1;a[nn]:=x; exit(nn); 8 end; 9 10 procedure insert(var t,x:longint); 11 begin 12 if t=0 then 13 begin 14 t:=new(x); 15 exit; 16 end; 17 inc(size[t]); 18 if x<a[t] then insert(l[t],x) 19 else insert(r[t],x); 20 end; 21 function search(t,x:longint):longint; 22 begin 23 search:=0; 24 while t<>0 do 25 begin 26 if (a[t]<=x)and(a[t]>search) then 27 search:=a[t]; 28 if x<a[t] then 29 t:=l[t] 30 else t:=r[t]; 31 end; 32 end; 33 function delete(var t:longint; x:longint):longint; 34 var rr,k:longint; 35 begin 36 dec(size[t]); 37 if (x=a[t])or((x<a[t])and(l[t]=0))or((x>a[t])and(r[t]=0)) then 38 begin 39 rr:=a[t]; 40 if (l[t]=0)or(r[t]=0) then 41 t:=l[t]+r[t] 42 else a[t]:=delete(l[t],a[t]+1); 43 exit(rr); 44 end 45 else if a[t]>x then exit(delete(l[t],x)) 46 else exit(delete(r[t],x)); 47 end; 48 procedure sort1(l,r: longint); 49 var 50 i,j,xx,yy: longint; 51 begin 52 i:=l; 53 j:=r; 54 xx:=an[(l+r) div 2]; 55 repeat 56 while an[i]<xx do 57 inc(i); 58 while xx<an[j] do 59 dec(j); 60 if not(i>j) then 61 begin 62 yy:=an[i]; 63 an[i]:=an[j]; 64 an[j]:=yy; 65 yy:=bn[i]; 66 bn[i]:=bn[j]; 67 bn[j]:=yy; 68 inc(i); 69 j:=j-1; 70 end; 71 until i>j; 72 if l<j then 73 sort1(l,j); 74 if i<r then 75 sort1(i,r); 76 end; 77 procedure sort2(l,r: longint); 78 var 79 i,j,xx,yy: longint; 80 begin 81 i:=l; 82 j:=r; 83 xx:=am[(l+r) div 2]; 84 repeat 85 while am[i]<xx do 86 inc(i); 87 while xx<am[j] do 88 dec(j); 89 if not(i>j) then 90 begin 91 yy:=am[i]; 92 am[i]:=am[j]; 93 am[j]:=yy; 94 yy:=bm[i]; 95 bm[i]:=bm[j]; 96 bm[j]:=yy; 97 inc(i); 98 j:=j-1; 99 end; 100 until i>j; 101 if l<j then 102 sort2(l,j); 103 if i<r then 104 sort2(i,r); 105 end; 106 107 begin 108 readln(n,m); 109 for i:=1 to n do 110 readln(an[i],bn[i]); 111 for i:=1 to m do 112 readln(am[i],bm[i]); 113 sort1(1,n);sort2(1,m); 114 j:=1; 115 for i:=1 to m do 116 begin 117 if nnn>n then break; 118 while (an[j]<=am[i])and(j<=n) do 119 begin 120 insert(root,bn[j]); 121 inc(j); 122 end; 123 xx:=search(root,bm[i]); 124 if xx<>0 then 125 begin 126 inc(nnn); 127 ans:=ans+am[i]; 128 delete(root,xx); 129 end; 130 end; 131 writeln(ans); 132 end.
-------------------------------------------------------------------------
花有重开日,人无再少年