ENG  RUSTimus Online Judge
Online Judge
Problems
Authors
Online contests
About Online Judge
Frequently asked questions
Site news
Webboard
Links
Problem set
Submit solution
Judge status
Guide
Register
Update your info
Authors ranklist
Current contest
Scheduled contests
Past contests
Rules
back to board

Discussion of Problem 1167. Bicolored Horses

why TLE??? (Dynamic Programming) THANKS
Posted by sashimi 4 Feb 2005 23:40
const
  maxn=500;
var
  n,k:integer;
  s:array[1..maxn]of byte;
  f:array[1..maxn,1..maxn]of integer;
procedure init;
var i,j:integer;
begin
{  assign(input,'in.in');reset(input);}
  readln(n,k);
  for i:=1 to n do readln(s[i]);
end;

function g(p1,p2:integer):integer;
var i,sum:integer;
begin
  sum:=0;
  for i:=p1 to p2 do if s[i]=1 then inc(sum);
  g:=(p2-p1+1-sum)*sum;
end;

procedure dp;
var i,j,mik,i2,t:integer;
begin
  for i:=1 to n do
    begin
      if i<k then mik:=i else mik:=k;
      for j:=1 to mik do
        begin
          f[i,j]:=maxint;
          if j=1 then f[i,j]:=g(1,i)
          else
            for i2:=1 to i-j+1 do
              begin
                t:=f[i-i2,j-1]+g(i-i2+1,i);
                if t<f[i,j] then f[i,j]:=t;
              end;
        end;
    end;
end;

{=============main==============}
begin
init;
dp;
writeln(f[n,k]);
end.
Your algo is O(n^3) .But it has better O(n^2) and best O(n) algo.
Posted by Neumann 5 Feb 2005 14:12
Re: Your algo is O(n^3) .But it has better O(n^2) and best O(n) algo.
Posted by bug27 4 May 2005 20:40
How to solve it in O(n) time?
Re: Your algo is O(n^3) .But it has better O(n^2) and best O(n) algo.
Posted by Trần Quang Chung 10 Jun 2006 09:30
How to slove it in (n^2). plz