51 nod 演算法馬拉松28 先序遍歷與後序遍歷

2021-08-07 17:28:05 字數 1886 閱讀 8226

先序遍歷與後序遍歷

scape

(命題人)

tangjz

(測試)

基準時間限制:1 秒 空間限制:131072 kb 分值: 40

對於給定的乙個二叉樹的先序遍歷和後序遍歷,輸出有多少種滿足條件的二叉樹。

兩棵二叉樹不同當且僅當對於某個x,x的左兒子編號不同或x的右兒子編號不同。

input

第一行乙個正整數n(3<=n<=10000),表示二叉樹的節點數,節點從1到n標號。

第二行n個整數a[i](1<=a[i]<=n),表示二叉樹的先序遍歷。

第三行n個整數b[i](1<=b[i]<=n),表示二叉樹的後序遍歷。

output

輸出乙個整數表示有多少種方案。保證至少有1種方案。
input示例

3

1 2 3

2 3 1

output示例

1

這道題比較簡單,按照先序遍歷和後序遍歷大概將一棵樹構建出來。從根節點開始遍歷,當乙個節點只有乙個兒子時,方案數乘2。

var

n,i,max,lans,j,x:longint;

a,b,ans:array[1..10000] of longint;

son:array[1..10000,1..2] of longint;

procedure dfs(la,ra,lb,rb,k:longint);

var i:longint;

begin

if rb=0 then exit;

if a[la]=b[rb] then

begin

if son[k,1]=0 then son[k,1]:=a[la] else son[k,2]:=a[la];

dfs(la+1,ra,lb,rb-1,la);

exit;

end;

for i:=rb downto lb do

if b[i]=a[la] then

begin

dfs(la,ra-rb+i,lb,i,k);

dfs(ra-rb+i+1,ra,i+1,rb,k);

break;

end;

end;

begin

ans[1]:=1;lans:=1;

readln(n);

for i:=1 to n do read(a[i]);

for i:=1 to n do read(b[i]);

dfs(2,n,1,n-1,1);

for i:=1 to n do

begin

if (son[i,1]<>0)and(son[i,2]<>0) then continue;

if (son[i,1]=0)and(son[i,2]=0) then continue;

x:=0;

for j:=1 to lans do

begin

ans[j]:=ans[j]*2+x;

if ans[j]>=10 then

begin

x:=ans[j] div 10;

ans[j]:=ans[j] mod 10;

end else x:=0;

end;

if x>0 then

begin

inc(lans);

ans[lans]:=x;

end;

end;

for i:=lans downto 1 do write(ans[i]);

end.

51nod演算法馬拉松32

比賽鏈結 馬拉松是真的難 應該是我太菜了tnt 同bzoj1534 題解戳這裡 n個有標號的點,其中m個是葉子節點。問有多少數的形態。include include include include include using namespace std typedef long long ll co...

51nod演算法馬拉松15

智力徹底沒有了。看來再也拿不到獎金了qaq。a b君的遊戲 因為資料是9b1l,所以我們可以hash試一下資料。include include include include define rep i,s,t for int i s i t i define dwn i,s,t for int i ...

51nod演算法馬拉松13

a 取餘最長路 不難發現路徑可以拆成三條線段,只要知道兩個轉折點的位置就能計算出答案。設sum i,l,r 表示第i行從l到r元素的和,則答案可以表示為sum 1,1,x sum 2,x,y sum 3,y,n p。字首和一下轉化成 s3 n s3 y 1 s2 y s1 x s2 x 1 p,從小...