NOIP2011T4 表达式的值

 

 

type
    pair=array[0..1]of longint;
var
    l,i,j,kh:longint;
    ans,zero:pair;
    st:array[1..50000]of longint;
    dis:array[1..100000]of longint;
    ch:array[1..100000]of char;
function f(l,r:longint):pair;
var i:longint; x,y:pair;
begin
    if l>r then exit(zero);
    i:=r;
    while i>=l do
    begin
        case ch[i] of
            '+':break;
            ')':i:=dis[i];
        end;
        dec(i);
    end;
    if i<l then
    begin
        i:=r;
        while i>=l do
        begin
            case ch[i] of
                '*': break;
                ')': i:=dis[i];
            end;
            dec(i);
        end;
    end;
    if i<l then exit(f(l+1,r-1));
    x:=f(l,i-1);
    y:=f(i+1,r);
    if ch[i]='*' then
    begin
        f[0]:=(x[0]*y[0]+x[0]*y[1]+x[1]*y[0]) mod 10007;
        f[1]:=(x[1]*y[1]) mod 10007;
    end;
    if ch[i]='+' then
    begin
        f[0]:=x[0]*y[0] mod 10007;
        f[1]:=(x[0]*y[1]+x[1]*y[0]+x[1]*y[1]) mod 10007;
    end;
end;

begin
    assign(input,'exp.in'); reset(input);
    assign(output,'exp.out'); rewrite(output);
    readln(l);
    kh:=0;
    for i:=1 to l do read(ch[i]);
    for i:=l downto 1 do
        case ch[i] of
            ')': begin inc(kh); st[kh]:=i; end;
            '(': begin dis[st[kh]]:=i; dec(kh); end;
        end;
    zero[0]:=1; zero[1]:=1;
    ans:=f(1,l);
    writeln(ans[0]);
    close(input); close(output);
end.

 

posted @ 2013-10-23 17:51  qilinart  阅读(218)  评论(0编辑  收藏  举报