poj 1502 最段路径
连接:http://poj.org/problem?id=1502
5 50 30 5 100 20 50 10 x x 10
第一行表示有 n 个点,之后第二行的第一个数表示 (2,1)的距离;第三行的第一个数表示 (3,1),第二个数表示 (3,2)。以此类推
求的是 the minimum communication time required to broadcast a message from the first processor to all the other processors
从题目 Once the first processor has sent the message to another, those two can then send messages to two other hosts at the same time. Then there will be four hosts that can send, and so on.
我们只要求出每条边到 1 点的距离,然后求出最长的
可以用 floyd 求出每条边 (练练手) ,也可以用 dijkstra
解法 1
/* * CreateTime: 2015-03-16 15:09:33 */ #include <cstdio> #include <algorithm> #include <cstdlib> using std::min; using std::max; const int maxn = 105; #define inf 0x3fffffff int n; int g[maxn][maxn]; void floyd() { for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { g[i][j] = min(g[i][j], g[i][k] + g[k][j]); } } } } int main(void) { scanf("%d", &n); char str[100]; for (int i = 2; i <= n; i++) { for (int j = 1; j < i; j++) { scanf("%s", str); if (str[0] == ‘x‘) { g[i][j] = g[j][i] = inf; } else { g[i][j] = g[j][i] = atoi(str); } } } floyd(); int ans = 0; for (int i = 1; i <= n; i++) { ans = max(ans, g[i][1]); } printf("%d\n", ans); return 0; }
解法 2
/* * CreateTime: 2015-03-16 14:44:57 */ #include <cstdio> #include <cstring> #include <algorithm> #include <cstdlib> using std::min; using std::max; #define inf 0x3fffffff const int maxn = 105; int n; int dis[maxn]; int g[maxn][maxn]; bool v[maxn]; void dijkstra() { for (int i = 1; i <= n; i++) { dis[i] = inf; v[i] = 0; } dis[1] = 0; for (int i = 1; i <= n; i++) { int mark = -1; int mindis = inf; for (int j = 1; j <= n; j++) { if (v[j] == 0 && dis[j] < mindis) { mindis = dis[j]; mark = j; } } v[mark] = 1; for (int j = 1; j <= n; j++) { if (v[j] == 0) { dis[j] = min(dis[j], dis[mark] + g[mark][j]); } } } } int main(void) { scanf("%d", &n); char str[100]; for (int i = 2; i <= n; i++) { for (int j = 1; j < i; j++) { scanf("%s", str); if (str[0] == ‘x‘) { g[i][j] = g[j][i] = inf; } else { g[i][j] = g[j][i] = atoi(str); } } } dijkstra(); int ans = 0; for (int i = 2; i <= n; i++) { ans = max(ans, dis[i]); } printf("%d\n", ans); return 0; }