2569. 【NOIP2011模拟9.17】旅行 (StandardIO)Description

来源:互联网 发布:java ll 和 编辑:程序博客网 时间:2024/04/29 12:46

2569. 【NOIP2011模拟9.17】旅行 (StandardIO)Description

X先生来到了一个奇怪的国家旅行。这个国家有N个城市,每个城市均有且仅有一个机场,但是这机场所有航班只飞往一个城市。每个城市有一个游览价值,第i个城市的游览价值为A[i]。
现在他想知道,从第i个城市出发,并只坐飞机飞往下一个城市,游览价值之和最多是多少(一个城市游览多次只计算1次游览价值)

Input

输入文件travel.in的第1行为一个正整数N。
第2行有N个非负整数A[i],表示了每个城市的游览价值。
第3行有N个正整数F[i],表示第i个城市的航班飞往的城市为F[i],可能出现F[i] = i的情况。

Output

输出文件travel.out包括N行,第i行包含一个非负整数,表示从第i个城市出发游览价值之和的最大值为多少。

Sample Input

8

5 4 3 2 1 1 1 1

2 3 1 1 2 7 6 8

Sample Output

12

12

12

14

13

2

2

1

Hint

对于20%的数据,N≤10;
对于40%的数据,N≤1000;
对于100%的数据,N≤200000,A[i]≤10000,F[i]≤N。

 

 

暴力找一个链,然后算出每个点的值,中间过程保留下来就好了,有环的话就全是环的最大点的值

 

const maxn=2000000;var flag,a,b,f,s:array [0..maxn] of longint; i,j,n,ans,p,q:longint; jiba:boolean;procedure dfs(x,dep:longint);var i,j:longint;begin flag[x]:=q; ifflag[f[x]]=0 then dfs(f[x],dep+1)                   else                   begin                    if flag[f[x]]=q thenp:=f[x];                    s[dep]:=a[x]+b[f[x]];                   end; ifjiba then s[dep]:=s[dep+1]+a[x]; jiba:=true; b[x]:=s[dep];end; procedure hjy(x,s:longint);var i,j:longint;begin b[x]:=s; ifx<>p then hjy(f[x],s);end; begin readln(n); fori:=1 to n do  read(a[i]); readln; fori:=1 to n do  read(f[i]);  fori:=1 to n do begin  ifflag[i]=0 then   begin   inc(q);   p:=0;   jiba:=false;   dfs(i,1);    ifp<>0 then hjy(f[p],b[p]);   end; writeln(b[i]); ans:=0; end;end.

 

2 0
原创粉丝点击