E. Analysis of pathes in functional Graph
You are given a functional graph. It is a directed graph with which from each vertex goes exactly one arc. The vertices is numerated from 0 to n -1.
Graph is given as the array F0, F1, ..., fn -1, where f c10>I -the number of vertex to which goes the-arc from the vertex I. Besides you is given array with weights of the arcs w0, w1, ..., w n -1, where wi -the arc weight from i to F i.
The graph from the first sample test.
Also you is given the integer k (the length of the path) and you need to find for each vertex the numbers s i and mi, where:
- s i -the sum of the weights of all arcs of the path with length equals- K which starts from the Vertex i;
- m i -the minimal weight from all arcs on the path with length K which starts from the Verte x i.
The length of the path is the number of arcs in this path.
Input
The first line contains the integers n, k (1≤ n ≤105, 1≤ k ≤1010). The second line contains the sequence F0, F1, ..., fn -1 ( C16>0≤ FI < n) and the third-the sequence w0, w1, ..., wn -1 (0≤ wi ≤108).
Output
Print n lines, the pair of integers si, mi in each line.
Examplesinput
7 3
1 2 3 4 3 2 6
6 3 1 4 2 2 3
Output
10 1
8 1
7 1
10 2
8 2
7 1
9 3
Input
4 4
0 1 2 3
0 1 2 3
Output
0 0
4 1
8 2
12 3
Input
5 3
1 2 3) 4 0
4 1 2) 14 3
Output
7 1
17 1
19 2
21 3
8 1
#include <cstdio>#include<cmath>#include<map>#include<cstring>#include<algorithm>#defineFi first#defineSe Secondusing namespaceStd;typedefLong LongLl;typedef pair<ll,int>PII;Const intn=1e5+5; LL ws[n][ +],k;intf[n][ +],wm[n][ +],n;voidBZ () { for(intj=1;(1ll<<j) <=k;j++) for(intI=0; i<n;i++) {F[i][j]=f[f[i][j-1]][j-1]; WS[I][J]=ws[i][j-1]+ws[f[i][j-1]][j-1]; WM[I][J]=min (wm[i][j-1],wm[f[i][j-1]][j-1]); }}pii Query (intu) {PII res; res.fi=0, res.se=1e8; for(intI=0;i< +; i++) if(k& (1ll<<i)) res.fi+=ws[u][i],res.se=min (wm[u][i],res.se), u=F[u][i]; returnRes;}intMain () {scanf ("%d%i64d",&n,&k); for(intI=0; i<n;i++) scanf ("%d", &f[i][0]); for(intI=0; i<n;i++) scanf ("%d", &wm[i][0]), ws[i][0]=wm[i][0]; BZ (); for(intI=0; i<n;i++) {PII ans=query (i); printf ("%i64d%d\n", ans.fi,ans.se); } return 0;}
Codeforces 702E Analysis of pathes in functional Graph (multiply)