POJ 3268 Silver Cow Party [图论.最短路] 《挑战程序设计竞赛》2.5
2017-05-23 17:09
411 查看
2017-05-23
题目大意:
N头牛,分别住在N个不同的牧场,牧场标号1~N。这N个牧场之间有M条单向路。现在要在第X个牧场开Party,每头牛都会从各自的牧场沿最短路到X,然后再从X沿最短路回去。因为这里是单向路,所以来的路和回的路可能是不同的。现在要求所有的牛中,走路走的最长的那头牛走的路的长度。
题解:
需要求X牧场到所有其他牧场的最短距离,和所有其他牧场到X牧场的最短距离。
第一次写用的Floyd-Warshall 算法,超时。
实际上我们并不需要任意一对顶点之间的最短距离。我们用邻接表储存图G, 所以只需要对G调用Dijkstra计算X牧场到所有其他牧场的最短距离,在对G的反向图revG调用Dijkstra计算所有其他牧场到X牧场的最短距离。
代码:
题目大意:
N头牛,分别住在N个不同的牧场,牧场标号1~N。这N个牧场之间有M条单向路。现在要在第X个牧场开Party,每头牛都会从各自的牧场沿最短路到X,然后再从X沿最短路回去。因为这里是单向路,所以来的路和回的路可能是不同的。现在要求所有的牛中,走路走的最长的那头牛走的路的长度。
题解:
需要求X牧场到所有其他牧场的最短距离,和所有其他牧场到X牧场的最短距离。
第一次写用的Floyd-Warshall 算法,超时。
实际上我们并不需要任意一对顶点之间的最短距离。我们用邻接表储存图G, 所以只需要对G调用Dijkstra计算X牧场到所有其他牧场的最短距离,在对G的反向图revG调用Dijkstra计算所有其他牧场到X牧场的最短距离。
代码:
#include <iostream> #include <queue> #include <vector> #define MAXN 1010 #define INF 0x3f3f3f3f using namespace std; typedef pair<int, int> P; struct Edge { int to, cost; Edge(int to, int cost) { this->to = to; this->cost = cost; } }; vector<Edge> G[MAXN]; vector<Edge> revG[MAXN]; int N, M, X; int d[MAXN]; int revd[MAXN]; void dijkstra(vector<Edge> *G, int *d, int s) { fill(d, d+MAXN, INF); d[s] = 0; priority_queue<P, vector<P>, greater<P> > que; que.push(P(0, s)); while (!que.empty()) { P p = que.top(); que.pop(); int v = p.second; for (int i = 0; i < G[v].size(); i++) { Edge e = G[v][i]; if (d[v] + e.cost < d[e.to]) { d[e.to] = d[v] + e.cost; que.push(P(d[e.to], e.to)); } } } } int main() { ios::sync_with_stdio(false); cin >> N >> M >> X; for (int i = 0; i < M; i++) { int u, v, w; cin >> u >> v >> w; G[u].push_back(Edge(v, w)); revG[v].push_back(Edge(u, w)); } dijkstra(G, d, X); dijkstra(revG, revd, X); int ans = 0; for (int i = 1; i <= N; i++) { ans = max(ans, d[i] + revd[i]); } cout << ans << endl; return 0; }
相关文章推荐
- poj 3268 Silver Cow Party 图论 最短路
- POJ 3268 - Silver Cow Party(最短路dijkstra)
- 文章标题 POJ 3268 : Silver Cow Party (最短路--spfa)
- POJ 3268 Silver Cow Party 最短路
- poj 3268 Silver Cow Party(最短路)
- Poj 3268 Silver Cow Party (最短路)
- POJ 3268 Silver Cow Party(最短路dijkstra)
- POJ 3268 Silver Cow Party 最短路
- poj-3268 Silver Cow Party (最短路-spfa-求到同一起点,同一终点的最短路)
- POJ 3268 Silver Cow Party 最短路
- poj 3268 Silver Cow Party (最短路算法的变换使用 【有向图的最短路应用】 )
- poj 3268 Silver Cow Party (最短路算法的变换使用 【有向图的最短路应用】 )
- poj--3268--Silver Cow Party(最短路)(建反向图)
- POJ 3268 Silver Cow Party(最短路 dijkstra求任意两点最短路)
- POJ 3268 Silver Cow Party [双向最短路求最大值]
- POJ 3268 Silver Cow Party (最短路,置换矩阵)
- poj Silver Cow Party 3268 (来回单向最短路)好题
- Poj 3268 Silver Cow Party + Poj 1511 Invitation Cards (最短路反向建图)
- poj 3268 Silver Cow Party(最短路)
- POJ-3268-Silver Cow Party [最短路][Dijkstra]