CF702E Analysis of Pathes in Functional Graph
倍增练习题。
基环树上倍增一下维护维护最小值和权值和,注意循环的时候$j$这维作为状态要放在外层循环,平时在树上做的时候一个一个结点处理并不会错,因为之前访问的结点已经全部处理过了。
时间复杂度$O(nlogk)$。
Code:
#include <cstdio> #include <cstring> using namespace std; typedef long long ll; const int N = 1e5 + 5; const int Lg = 35; const int inf = 0x3f3f3f3f; int n, to[N][Lg]; ll stp, val[N], sum[N][Lg], minn[N][Lg]; template <typename T> inline void read(T &X) { X = 0; char ch = 0; T op = 1; for(; ch > '9'|| ch < '0'; ch = getchar()) if(ch == '-') op = -1; for(; ch >= '0' && ch <= '9'; ch = getchar()) X = (X << 3) + (X << 1) + ch - 48; X *= op; } template <typename T> inline void chkMin(T &x, T y) { if(y < x) x = y; } template <typename T> inline T min(T x, T y) { return x > y ? y : x; } inline void solve(int x) { ll resSum = 0LL, resMin = inf, tmp = stp; for(int i = 34; i >= 0; i--) if((tmp >> i) & 1) { resSum += sum[x][i]; chkMin(resMin, minn[x][i]); x = to[x][i]; } printf("%lld %lld\n", resSum, resMin); } int main() { read(n), read(stp); for(int i = 1; i <= n; i++) read(to[i][0]), to[i][0]++; for(int i = 1; i <= n; i++) read(val[i]); memset(minn, 0x3f, sizeof(minn)); for(int i = 1; i <= n; i++) sum[i][0] = minn[i][0] = val[i]; for(int j = 1; j <= 34; j++) for(int i = 1; i <= n; i++) { to[i][j] = to[to[i][j - 1]][j - 1]; minn[i][j] = min(minn[i][j - 1], minn[to[i][j - 1]][j - 1]); sum[i][j] = sum[i][j - 1] + sum[to[i][j - 1]][j - 1]; } /* for(int i = 1; i <= n; i++) printf("%lld ", sum[i][1]); printf("\n"); */ for(int i = 1; i <= n; i++) solve(i); return 0; }