POJ 1125 Stockbroker Grapevine
题意:有n个人,传播谣言,每个人向其他人传播的时间作为边权,构成一个有向图,问把谣言告诉谁能最快传到所有人,输出这个人和最短时间。
解法:最短路。一个人传到所有人的最短时间即他到所有人最短路的最大值,求所有最大值的最小值即为所求。分别用了floyd和dijsktra写了一下……(一直以为dijsktra就是个广搜而已呢(逃
代码:
floyd
#include<stdio.h> #include<iostream> #include<algorithm> #include<string> #include<string.h> #include<math.h> #include<limits.h> #include<time.h> #include<stdlib.h> #include<map> #include<queue> #include<set> #include<stack> #include<vector> #define LL long long using namespace std; int n; int dis[105][105]; const int maxn = 0x3f3f3f3f; void floyd() { for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { for(int k = 1; k <= n; k++) { dis[j][k] = min(dis[j][i] + dis[i][k], dis[j][k]); } } } } int main() { while(~scanf("%d", &n) && n) { memset(dis, maxn, sizeof dis); for(int i = 1; i <= n; i++) { int m; scanf("%d", &m); for(int j = 0; j < m; j++) { int a, b; scanf("%d%d", &a, &b); dis[i][a] = b; } } floyd(); int ans = INT_MAX, pos = 0; for(int i = 1; i <= n; i++) { int res = -1; for(int j = 1; j <= n; j++) { if(i == j) continue; int tmp = dis[i][j]; if(tmp == maxn) { res = -1; break; } else res = max(res, tmp); } if(res != -1) { if(res < ans) { ans = res; pos = i; } } } if(pos) { printf("%d %d\n", pos, ans); } else puts("disjoint"); } return 0; }
dijsktra
#include<stdio.h> #include<iostream> #include<algorithm> #include<string> #include<string.h> #include<math.h> #include<limits.h> #include<time.h> #include<stdlib.h> #include<map> #include<queue> #include<set> #include<stack> #include<vector> #define LL long long using namespace std; int n; int stockbroker[105][105]; bool vis[105]; int dis[105][105]; const int maxn = 0x3f3f3f3f; struct node { int vertex; int value; node(int vertex, int value) : vertex(vertex), value(value) {} node() {} }; queue <node> q; void dij() { for(int i = 1; i <= n; i++) { memset(vis, 0, sizeof vis); q.push(node(i, 0)); while(!q.empty()) { node tmp = q.front(); q.pop(); vis[tmp.vertex] = true; for(int j = 1; j <= n; j++) { if(stockbroker[tmp.vertex][j] < 20) { dis[i][j] = min(dis[i][j], tmp.value + stockbroker[tmp.vertex][j]); if(!vis[j]) q.push(node(j, tmp.value + stockbroker[tmp.vertex][j])); } } } } } int main() { while(~scanf("%d", &n) && n) { memset(dis, maxn, sizeof dis); for(int i = 0; i < 105; i++) { for(int j = 0; j < 105; j++) { stockbroker[i][j] = 20; if(i == j) stockbroker[i][j] = 0; } } for(int i = 1; i <= n; i++) { int m; scanf("%d", &m); for(int j = 0; j < m; j++) { int a, b; scanf("%d%d", &a, &b); stockbroker[i][a] = b; dis[i][a] = b; } } dij(); int ans = INT_MAX, pos = 0; for(int i = 1; i <= n; i++) { int res = -1; for(int j = 1; j <= n; j++) { if(i == j) continue; int tmp = dis[i][j]; if(tmp == maxn) { res = -1; break; } else res = max(res, tmp); } if(res != -1) { if(res < ans) { ans = res; pos = i; } } } if(pos) { printf("%d %d\n", pos, ans); } else puts("disjoint"); } return 0; }