Codeforces 702E - Analysis of Pathes in Functional Graph 二进制
题目:http://codeforces.com/contest/702/problem/E
题意:
给一个有向图,每个节点从1到n,给出每个节点直接指向的节点fi和边,要求你找出两个数:
1. 从v点出发,走k个节点所经过的边权值之和si
2. 从v点出发,走k个节点所经过的最小边mi
Input
The first line contains two integers n, k (1 ≤ n ≤ 10^5, 1 ≤ k ≤ 10^10). The second line contains the sequence f0, f1, …, fn - 1 (0 ≤ fi < n) and the third — the sequence w0, w1, …, wn - 1 (0 ≤ wi ≤ 10^8).
Output
Print n lines, the pair of integers si, mi in each line.
分析:
这题的思想像是快速幂,方法像是RMQ , 相当于把k分解成二进制,然后分别相加。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF=1e18;
const int maxb=36;
const int maxn=1e5+9;
int n,f[maxn][maxb];
ll k,sum[maxn][maxb],mn[maxn][maxb];
void Print(int v,ll k)
{
ll tsum=0,tmn=INF;
for(int i=maxb-1;i>=0;i--)if((1LL<<i)<=k){
tsum+=sum[v][i];
tmn=min(tmn,mn[v][i]);
v=f[v][i];
k-=(1LL<<i);
}
printf("%I64d %I64d\n",tsum,tmn);
}
int main()
{
scanf("%d%I64d",&n,&k);
for(int i=0;i<n;i++)scanf("%d",&f[i][0]);
for(int i=0;i<n;i++){
scanf("%I64d",&sum[i][0]);
mn[i][0]=sum[i][0];
}
for(int j=1;j<maxb;j++)
for(int i=0;i<n;i++){
f[i][j]=f[f[i][j-1]][j-1];
sum[i][j]=sum[i][j-1]+sum[f[i][j-1]][j-1];
mn[i][j]=min(mn[i][j-1],mn[f[i][j-1]][j-1]);
}
for(int i=0;i<n;i++)
Print(i,k);
return 0;
}