Stockbroker Grapevine
题目链接:Click Here~
题目分析:
不知道这题是为了考英语阅读理解还是考算法。国外的题目做起来就是蛋疼。
题目意思是:给你n个点,叫你求出从n个点中选出一个点到到其他n-1个点的最长时间time,而又从这n个点中选出time最小的。靠!看了好久都没懂那题目啥意思。
算法分析:
其实本质就是n次最短路的问题。过程被题目描述的高端了。所以,我用了SPFA和FLOYD算法试了一下,都可以过。而且,,,。数据中没有找不到的情况。
Spfa版:
#include <iostream> #include <algorithm> #include <vector> #include <queue> #include <cstdio> #include <cstring> using namespace std; struct Edge{ int from,to,cost; //从from到to的时间 }; class StockBroker{ public: static const int maxn = 100+5; static const int INF = 1e8; StockBroker(int n){ this->n = n; for(int i = 0;i <= n;++i) G[i].clear(); edges.clear(); } void Init(); void AddEdge(int from,int to,int cost); int Spfa(int s); void Print(); private: int n,m; vector<Edge> edges; vector<int> G[maxn]; }; void StockBroker::AddEdge(int from,int to,int cost) // 加边 { edges.push_back((Edge){from,to,cost}); m = edges.size(); G[from].push_back(m-1); } int StockBroker::Spfa(int s) { queue<int> Q; int d[maxn]; bool inq[maxn]; for(int i = 0;i <= n;++i) d[i] = INF,inq[i] = false; d[s] = 0; Q.push(s); while(!Q.empty()){ int u = Q.front(); Q.pop(); inq[u] = false; for(int i = 0;i < (int)G[u].size();++i){ Edge& e = edges[G[u][i]]; if(d[e.to]>d[u]+e.cost){ d[e.to] = d[u] + e.cost; if(!inq[e.to]){ inq[e.to] = true; Q.push(e.to); } } } } int maxv = -INF; for(int i = 1;i <= n;++i) maxv = max(maxv,d[i]); return maxv; } int main() { int n,m; while(scanf("%d",&n),n) { int u,c; StockBroker spfa(n); for(int i = 1;i <= n;++i){ scanf("%d",&m); while(m--){ scanf("%d%d",&u,&c); spfa.AddEdge(i,u,c); } } int pos=1,ans = 100000; for(int i = 1;i <= n;++i){ //调用n次最短路算法 int tmp = spfa.Spfa(i); if(tmp < ans){ pos = i; ans = tmp; } } printf("%d %d\n",pos,ans); } return 0; }
Floyd版:
#include <iostream> #include <vector> #include <cstdio> #include <cstring> using namespace std; class StockBroker{ public: static const int maxn = 100+5; static const int INF = 1e8; StockBroker(int n){ this->n = n; for(int i = 0;i <= n;++i) for(int j = 0;j <= n;++j) d[i][j] = (i==j?0:INF); } void Init(int from,int to,int cost); void AddEdge(int from,int to,int cost); void Floyd(); void Print(); private: int n,m; int d[maxn][maxn]; }; inline void StockBroker::Init(int from,int to,int cost) { d[from][to] = cost; } void StockBroker::Floyd() { for(int k = 1;k <= n;++k) for(int i = 1;i <= n;++i) for(int j = 1;j <= n;++j) if(d[i][j] > d[i][k]+d[k][j]) d[i][j] = d[i][k]+d[k][j]; } void StockBroker::Print() { int pos=1,ans = INF; for(int i = 1;i <= n;++i){ int maxv = -INF; for(int j = 1;j <= n;++j){ if(maxv < d[i][j]) maxv = d[i][j]; } if(ans > maxv){ ans = maxv; pos = i; } } printf("%d %d\n",pos,ans); } int main() { int n,m; while(scanf("%d",&n),n) { int u,cost; StockBroker floyd(n); for(int i = 1;i <= n;++i){ scanf("%d",&m); while(m--){ scanf("%d%d",&u,&cost); floyd.Init(i,u,cost); } } floyd.Floyd(); floyd.Print(); } return 0; }
POJ Stockbroker Grapevine(最短路算法),布布扣,bubuko.com
POJ Stockbroker Grapevine(最短路算法)
原文:http://blog.csdn.net/zhongshijunacm/article/details/21599611