The pre-treatment of this problem slightly moving brain, in fact, is a bare replacement group =-=, no pressure.
1 Constmaxn=1000001;2 varN,i,j,minx,tem,now,tmin,len:longint;3 Cursum,sum:int64;4pos,num,tnum,ys:array[0.. MAXN] of Longint;5p:array[0.. MAXN] of Boolean;6 function min (a,b:longint): Longint;7 begin8 ifA>B then exit (b)9 Elseexit (a);Ten end; One begin A READLN (n); -minx:=MAXN; - fori:=1to n Do the begin - read (tnum[i]); -minx:=min (minx,tnum[i]); - end; + Readln; - fori:=1to n Do + begin A read (TEM); atnum[i]:=Tnum[tem]; -ys[tem]:=i; - end; - Readln; - fori:=1to n Do - begin in read (TEM); -pos[ys[tem]]:=i; to end; +Fillchar (P,sizeof(p),true); - fori:=1to n Do the ifP[i] Then * begin $cursum:=0;Panax Notoginsengnow:=i; -len:=0; thetmin:=Num[i]; + whileP[now] Do A begin the Inc (LEN); +tmin:=min (Tmin,num[now]); - Inc (Cursum,num[now]); $p[now]:=false; $now:=Pos[now]; - end; - ifLen>1Then Inc (Sum,cursum); the ifLen>2Then Inc (Sum,min (tmin* (len-2), minx* (len+1)+tmin)); - end;Wuyi writeln (sum); theEnd.
P1119: [Poi2009]slo