您的位置:首页 > 其它

Educational Codeforces Round 15 E 树上倍增 RMQ思想

2016-08-01 15:31 423 查看
链接:戳这里

E. Analysis of Pathes in Functional Graph

time limit per test2 seconds
memory limit per test512 megabytes
inputstandard input
outputstandard output
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1.

Graph is given as the array f0, f1, ..., fn - 1, where fi — the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights of the arcs w0, w1, ..., wn - 1, where wi — the arc weight from i to fi.



The graph from the first sample test.

Also you are given the integer k (the length of the path) and you need to find for each vertex two numbers si and mi, where:

si — the sum of the weights of all arcs of the path with length equals to k which starts from the vertex i;

mi — the minimal weight from all arcs on the path with length k which starts from the vertex i.

The length of the path is the number of arcs on this path.

Input

The first line contains two integers n, k (1 ≤ n ≤ 105, 1 ≤ k ≤ 1010). The second line contains the sequence f0, f1, ..., fn - 1 (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.

Examples

input

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

题意:

n个点n条边的图,每个节点都连向一个点,可以是自己。

问从该点到长度为k的路径上。输出路径权值总和以及路径上的最小值

思路:

学习了一下树上倍增。其实理解了RMQ写这个还很快的。

fa[j][i]=fa[fa[j][i-1]][i-1]  这个很关键啊   表示以j节点开始到长度为i的路径上  所到的节点

代码:

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<string>
#include<vector>
#include <ctime>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<iomanip>
#include<cmath>
#include<bitset>
#define mst(ss,b) memset((ss),(b),sizeof(ss))
///#pragma comment(linker, "/STACK:102400000,102400000")
typedef long long ll;
typedef long double lb;
#define INF (1ll<<60)-1
#define Max 1e9
using namespace std;
int n;
int fa[100100][40];
ll s[100100][40],m[100100][40],k;
int main(){
scanf("%d%I64d",&n,&k);
for(int i=0;i<n;i++) scanf("%d",&fa[i][0]);
for(int i=0;i<n;i++){
scanf("%I64d",&m[i][0]);
s[i][0]=m[i][0];
}
for(int i=1;(1LL<<i)<=k;i++){
for(int j=0;j<n;j++){
fa[j][i]=fa[fa[j][i-1]][i-1];
m[j][i]=min(m[j][i-1],m[fa[j][i-1]][i-1]);
s[j][i]=s[j][i-1]+s[fa[j][i-1]][i-1];
}
}
for(int i=0;i<n;i++){
ll mn=INF,sum=0;
int x=i;
for(int j=0;(1LL<<j)<=k;j++){
if((1LL<<j)&k){
mn=min(mn,m[x][j]);
sum+=s[x][j];
x=fa[x][j];
}
}
printf("%I64d %I64d\n",sum,mn);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: