{$A+,B-,C+,D+,E-,F-,G+,H+,I+,J+,K-,L+,M-,N+,O+,P+,Q+,R+,S+,T-,U-,V+,W-,X+,Y+,Z1}
{$MINSTACKSIZE $00004000}
{$MAXSTACKSIZE $00100000}
{$IMAGEBASE $00400000}
{$APPTYPE CONSOLE}

uses SysUtils, Math,testlib;
const     MIN_N      = 1;
          MAX_N      = 30;
          MIN_A      = -10000;
          MAX_A      =  10000;
type float = extended;
     integer = longint;
var n:integer;
    a:array[1..MAX_N] of integer;

function a2s(aname:string;aindex:integer):string;
begin
Result := aname + '[' + i2s(aindex) + ']';
end;
procedure readInput;
var i:integer;
begin
n := inf.ReadLongint;
if n < MIN_N then Quit(_FAIL,'bad input: n = ' + i2s(n) + ' < ' + i2s(MIN_N));
if n > MAX_N then Quit(_FAIL,'bad input: n = ' + i2s(n) + ' > ' + i2s(MAX_N));
inf.RequireNewLine(false);
for i:=1 to n do
  begin
  a[i] := inf.ReadLongint;
  if a[i] < MIN_A then Quit(_FAIL,'bad input: ' + a2s('a',i) + ' = ' + i2s(a[i]) + ' < ' + i2s(MIN_A));
  if a[i] > MAX_A then Quit(_FAIL,'bad input: ' + a2s('a',i) + ' = ' + i2s(a[i]) + ' > ' + i2s(MAX_A));
  end;
inf.RequireNewLine(false);
end;

function checkSolution(var f:InStream;z:TResult;const who:string) : integer;
var i,sum:integer;
    s:string;
    st:set of 1..MAX_N;
    x:array[1..MAX_N] of integer;
begin
s := 'Bad ' + who + ':';
Result := f.ReadLongint;
sum := 0;
f.RequireNewLine(false);
st := [];
for i:=1 to n do
  begin
  x[i] := f.ReadLongint;
  if (x[i] < 1) then Quit(z,s + a2s('x',i) + ' = ' + i2s(a[i]) + ' < ' + i2s(1));
  if (x[i] > n) then Quit(z,s + a2s('x',i) + ' = ' + i2s(a[i]) + ' > ' + i2s(n));
  if x[i] in st then Quit(z,s + 'vertex ' + i2s(a[i]) + ' visited twice');
  Include(st,x[i]);
  end;
for i:=2 to n do inc(sum,a[x[i-1]]+a[x[i]]);
if sum <> Result then
  Quit(z,s + ' sum = ' + i2s(sum) + ' <> ' + i2s(Result));
end;

var jury,user:integer;
    s:string;
begin
readInput;
jury := checkSolution(ans,_FAIL,'jury');
user := checkSolution(ouf,_WA,'output');
s := 'jury = ' + i2s(jury) + ' user = ' + i2s(user);
if jury < user then
  Quit(_WA,'contestant found not optimal solution' + ' ' + s);
if jury > user then
  Quit(_FAIL,'jury solution isn''''t minimal' + ' ' + s);
Quit(_OK,s);
end.
