NOIP2008 T4双栈排序(twostacks)

算法:图论

分析:这题的主要难度其实是在建图上,只要能分析出是二分图来,题目也理解的差不多了。
    首先看这样一种关系:存在k,使得i<j<k,且P[k]<P[i]<P[j],则如果满足这样一种关系,那么i和j一定不能压入同一个栈中,因为P[k]出栈之前,P[i]和P[j]都不能出栈,否则顺序就乱了,同理因为P[i]<P[j],所以i应该先出栈,而j>i,那么就成了P[j]先出栈了,顺序就混乱了。
    那么如果不满足这种关系呢,则会衍生出两种关系:
      1.对于任意k,i<j<k且P[i]<P[j],P[k]>P[i],这里当i出栈的时候,j和k不会相互影响。
      2.对于任意i<j,P[i]>P[j],如果是这样的话就形成了一个递减栈,这样的话小的后进先出,满足要求。
    其中如果我们要枚举k的话,复杂度会达到O(n3),对于N=1000的情况是无能为力的,因此对于P[k]我们可以采用O(1)的方法降低time,具体方法就是用b[i]表示i~n内的最小的a[i]值,这样就满足了i<j<k且P[k]<P[i]<P[j]了。
    然后就利用二分图,把不能在同一个栈里的都染上不同的颜色,如果出现颜色重复的就是无解。
    对于字典序取最小的问题,让它们优先进入栈S1,同时操作时也优先操作栈S1即可。

    最终就可以直接模拟输出了。

program twostacks;

const
 maxn=1000;

var
 color,s1,s2,a,b:array [0..maxn] of longint;
 n,top1,top2,r:longint;
 
procedure init;
var
 i:longint;
begin
 readln(n);
 for i:=1 to n do read(a[i]);
 close(input);
 for i:=n downto 1 do 
  begin
   b[i]:=a[i];
   if (i<n) and (b[i]>b[i+1]) then b[i]:=b[i+1];
   color[i]:=-1;
  end;
end;

procedure co(x,y:longint);
begin
 if (color[x]=-1) and (color[y]=-1) then
  begin
   color[x]:=0;
   color[y]:=1;  
  end
 else if (color[x]<>-1) and (color[y]=-1) then color[y]:=(color[x]+1) mod 2
 else if (color[y]<>-1) and (color[x]=-1) then color[x]:=(color[y]+1) mod 2
 else if (color[x]<>-1) and (color[y]<>-1) and (color[x]=color[y]) then
  begin
   writeln(0);
   close(output);
   halt;
  end;
end;

procedure find;
begin
 if s1[top1]=b[r]+1 then
  begin
   write('b',' ');
   inc(r);
   b[r]:=s1[top1];
   dec(top1); 
   find;
  end;
 if s2[top2]=b[r]+1 then
  begin
   write('d',' ');
   inc(r);
   b[r]:=s2[top2];
   dec(top2); 
   find;
  end;  
end;

procedure run;
var
 i:longint;
begin
 top1:=0;
 top2:=0;
 r:=0;
 b[r]:=0;
 for i:=1 to n do
  begin
   if color[i]=0 then
    begin
     write('a',' ');
     inc(top1);
     s1[top1]:=a[i];
     find;
     continue;     
    end;
   if color[i]=1 then
    begin
     write('c',' ');
     inc(top2);
     s2[top2]:=a[i];
     find;
    end;
  end;
 writeln;
end;

procedure main;
var
 i,j:longint;
begin
 for i:=1 to n-2 do
  begin
   for j:=i+1 to n-1 do
    begin
     if (a[i]<a[j]) and (b[j]<a[i]) then co(i,j);
    end;
  end;
 for i:=1 to n do if color[i]=-1 then color[i]:=0;
 run;
end;

begin
 assign(input,'twostacks.in'); reset(input);
 assign(output,'twostacks.out'); rewrite(output); 
 
 init;
 main;
 
 close(input); close(output);
end.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值