问题 C: Cow Relays
时间限制: 1 Sec 内存限制: 128 MB
提交: 32 解决: 11
[提交] [状态] [命题人:admin]
题目描述
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.
输入
* Line 1: Four space-separated integers: N, T, S, and E
* Lines 2..T+1: Line i+1 describes trail i with three space-separated integers: lengthi , I1i , and I2i
输出
* Line 1: A single integer that is the shortest distance from intersection S to intersection E that traverses exactly N cow trails.
样例输入
复制样例数据
2 6 6 4
11 4 6
4 4 8
8 4 9
6 6 8
2 6 9
3 8 9
样例输出
10
题意:无向图上求一点到另一点恰好经过k条边的最短路径
floyd+矩阵快速幂
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 200;
const int inf = 0x3f;
int num[1100];
int cnt;
int n, m, s, e;
struct Matrix {
int dis[maxn][maxn];
void init() {
memset(dis, inf, sizeof(dis));
}
} ans, a, temp,tema;
void cal(Matrix &q, Matrix &b, Matrix &c) {
for (int k = 0; k < cnt; k++) {
for (int i = 0; i < cnt; i++) {
for (int j = 0; j < cnt; j++)
q.dis[i][j] = min(q.dis[i][j], b.dis[i][k] + c.dis[k][j]);
}
}
}
void solve() {
ans.init();
temp.init();
tema.init();
for (int i = 0; i < cnt; i++)
ans.dis[i][i] = 0;
while (n) {
if (n & 1) {
cal(temp, ans, a);
ans = temp;
temp.init();
}
cal(tema, a, a);
a = tema;
tema.init();
n >>= 1;
}
}
int main() {
cin >> n >> m >> s >> e;
int u, v, val;
memset(num, -1, sizeof(num));
a.init();
cnt = 0;
for (int i = 1; i <= m; i++) {
cin >> val >> u >> v;
if (num[u] == -1) num[u] = cnt++;
if (num[v] == -1) num[v] = cnt++;
a.dis[num[u]][num[v]] = a.dis[num[v]][num[u]] = min(val, a.dis[num[u]][num[v]]);
}
solve();
cout << ans.dis[num[s]][num[e]] << endl;
return 0;
}