Description
给你n个点每个点都有k个出边,每条出边都指向某个节点,且有一个权值。
现在给你一个字符串,字符串中可能会有压缩字符,形如:[3A]。让你求经过字符串指定操作的总权值。
Sample Input
4 2
3 3 2 5
1 7 3 2
4 3 2 5
2 10 3 2
[3A]B[2A][2B]
10000
Sample Output
38
考虑倍增,对于每一个字符开一个倍增数组即可。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
int _min(int x, int y) {return x < y ? x : y;}
int _max(int x, int y) {return x > y ? x : y;}
int read() {
int s = 0, f = 1; char ch = getchar();
while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
return s * f;
}
int f[31][27][10010], s[31][27][10010];
char ss[130000];
int main() {
int n = read(), K = read();
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= K; j++) {
int x = read(), u = read();
f[0][j][i] = x, s[0][j][i] = u;
}
} scanf("%s", ss + 1); int len = strlen(ss + 1);
int x = 1, S = 0, mod = read();
for(int i = 1; i <= n; i++) for(int j = 1; j <= K; j++) s[0][j][i] %= mod;
for(int j = 1; j <= K; j++)
for(int i = 1; i <= 30; i++)
for(int k = 1; k <= n; k++) {
f[i][j][k] = f[i - 1][j][f[i - 1][j][k]];
s[i][j][k] = (s[i - 1][j][k] + s[i - 1][j][f[i - 1][j][k]]) % mod;
}
for(int i = 1; i <= len; i++) {
if(ss[i] == '[') {
int qq = 0; i++;
while(ss[i] >= '0' && ss[i] <= '9') qq = qq * 10 + ss[i] - '0', ++i;
for(int j = 30; j >= 0; j--) if(qq >= (1 << j)){
(S += s[j][ss[i] - 'A' + 1][x]) %= mod;
x = f[j][ss[i] - 'A' + 1][x];
qq -= 1 << j;
} ++i;
} else {
(S += s[0][ss[i] - 'A' + 1][x]) %= mod;
x = f[0][ss[i] - 'A' + 1][x];
}
} printf("%d\n", S);
return 0;
}