Advertisement
Guest User

ABBYY Cup 2.0 problem F solution

a guest
Apr 28th, 2012
2,096
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Delphi 1.43 KB | None | 0 0
  1. {$R-,S-,Q-,I-,O+}
  2. const inf = round(1e9);
  3. var
  4.   s: array [0..2010] of ansistring;
  5.   f: array [0..4010,0..2010] of longint;
  6.   lcp: array [0..2010] of longint;
  7.   n,k,i,j,q,cnt: longint;
  8.  
  9. procedure Sort(l,r:longint);
  10. var
  11.   i,j: longint;
  12.   x,tmp: ansistring;
  13. begin
  14.   i:=l; j:=r;
  15.   x:=s[l+random(r-l+1)];
  16.   repeat
  17.     while s[i] < x do inc(i);
  18.     while x < s[j] do dec(j);
  19.     if i <= j then
  20.     begin
  21.       tmp:=s[i]; s[i]:=s[j]; s[j]:=tmp;
  22.       inc(i); dec(j);
  23.     end;
  24.   until i > j;
  25.   if l < j then Sort(l,j);
  26.   if i < r then Sort(i,r);
  27. end;
  28.  
  29. function rec(l,r:longint):longint;
  30. var
  31.   id,i,j,p,left,right,cur: longint;
  32. begin
  33.   inc(cnt);
  34.   id:=cnt;
  35.   for i:=0 to r-l+1 do f[id,i]:=0;
  36.   if l < r then
  37.   begin
  38.     p:=l;
  39.     for i:=l+1 to r-1 do
  40.       if lcp[i] < lcp[p] then p:=i;
  41.     left:=rec(l,p);
  42.     right:=rec(p+1,r);
  43.     for i:=0 to p-l+1 do
  44.       for j:=0 to r-p do
  45.       begin
  46.         cur:=f[left,i]+f[right,j]+lcp[p]*i*j;
  47.         if cur > f[id,i+j] then f[id,i+j]:=cur;
  48.       end;
  49.   end;
  50.   rec:=id;
  51. end;
  52.  
  53. begin
  54.   randomize;
  55.   readln(n,k);
  56.   assert((1 <= k) and (k <= n) and (n <= 2000));
  57.   for i:=1 to n do readln(s[i]);
  58.   Sort(1,n);
  59.   for i:=1 to n-1 do
  60.   begin
  61.     q:=length(s[i]);
  62.     if length(s[i+1]) < q then q:=length(s[i+1]);
  63.     lcp[i]:=0;
  64.     for j:=1 to q do
  65.       if s[i,j] = s[i+1,j] then inc(lcp[i])
  66.       else break;
  67.   end;
  68.   cnt:=0;
  69.   rec(1,n);
  70.   writeln(f[1,k]);
  71. end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement