for (int k = 1; k <= n; k ++) for (int i = 1; i <= n; i ++) for (int j = 1; j <= n; j ++) if (m[i][k] + m[k][j] < m[i][j]) m[i][j] = m[i][k] + m[k][j];
matrix matrix_quick_pow(matrix a, ll k){ matrix ans = (matrix) {1, 0, 0, 1}; while (k > 0) { if (k & 1) ans = matrix_multi(ans, a); a = matrix_multi(a, a); k >>= 1; } return ans; }
intmain(){ cin >> n; matrix e_0 = (matrix) {1, 1, 1, 0}; matrix e_t; e_t = matrix_quick_pow(e_0, n - 2); ll ans = (e_t.a11 % P + e_t.a12 % P) % P; cout << ans << endl; return0; }
P2886 [USACO07NOV]牛继电器Cow Relays
For their physical fitness program, N (2 ≤ N ≤ 1,000,000) cows have decided to run a relay race using the T (2 ≤ T ≤ 100) cow trails throughout the pasture.
Each trail connects two different intersections (1 ≤ I1i ≤ 1,000; 1 ≤ I2i ≤ 1,000), each of which is the termination for at least two trails. The cows know the lengthi of each trail (1 ≤ lengthi ≤ 1,000), the two intersections the trail connects, and they know that no two intersections are directly connected by two different trails. The trails form a structure known mathematically as a graph.
To run the relay, the N cows position themselves at various intersections (some intersections might have more than one cow). They must position themselves properly so that they can hand off the baton cow-by-cow and end up at the proper finishing place.
Write a program to help position the cows. Find the shortest path that connects the starting intersection (S) and the ending intersection (E) and traverses exactly N cow trails.
int n = 0, k, m, s, t, d[maxn][maxn], a[maxn][maxn], map[1005];
voidmul(int a[maxn][maxn], int b[maxn][maxn]){ int t[maxn][maxn]; for (int i = 0; i < n; i ++) { for (int j = 0; j < n;j ++) { t[i][j] = 1e9; for (int k = 0; k < n; k ++) { if (t[i][j] > a[i][k] + b[k][j]) t[i][j] = a[i][k] + b[k][j]; } } } for (int i = 0; i < n; i ++) for (int j = 0; j < n; j ++) a[i][j] = t[i][j]; }
intmain(){ cin >> k >> m >> s >> t; memset(d, 0x3f, sizeof(d)); memset(a, 0x3f, sizeof(a)); memset(map, 0xff, sizeof(map)); // -1
// 由于数据关系,需要对数据进行过映射 while (m --> 0) { int l, u, v; cin >> l >> u >> v; if (map[u] == -1) map[u] = n ++; if (map[v] == -1) map[v] = n ++; d[map[u]][map[v]] = d[map[v]][map[u]] = l; } // a为图的单位矩阵,即A_0,只有对角线是0,其他都是无穷大 for (int i = 0; i < n; i ++) a[i][i] = 0; // 快速幂 while (k > 0) { if (k & 1) mul(a, d); mul(d, d); k /= 2; } cout << a[map[s]][map[t]] << endl; return0; }