[HDU 4725]The Shortest Path in Nya Graph[建图]
2015-10-25 02:21
351 查看
题目链接:[HDU 4725]The Shortest Path in Nya Graph[建图]
题意分析:
1到n点间,有边通过代价为w。点又在相应的层上,x层上的点可以到达x + 1和 x -1层上的任意一个点,代价为c。问:点1到点n的最小代价是?无法到达输出『-1』
解题思路:
这题可以在点和层之间连一条边,这里我们设n + 2 * x为层入口,n + 2*x - 1为层出口。这样把层拆开是避免同层上的点之间的距离变为0。
个人感受:
果然图见多了才有感觉,学习了~
具体代码如下:
题意分析:
1到n点间,有边通过代价为w。点又在相应的层上,x层上的点可以到达x + 1和 x -1层上的任意一个点,代价为c。问:点1到点n的最小代价是?无法到达输出『-1』
解题思路:
这题可以在点和层之间连一条边,这里我们设n + 2 * x为层入口,n + 2*x - 1为层出口。这样把层拆开是避免同层上的点之间的距离变为0。
个人感受:
果然图见多了才有感觉,学习了~
具体代码如下:
#include<cstdio> #include<cstring> #include<map> #include<queue> #define pii pair<int, int> using namespace std; const int INF = 0x7f7f7f7f; const int MAXN = 1e5 + 111; struct Node{ int to, w; Node(int _to, int _w): to(_to), w(_w){} }; vector<Node> G[3 * MAXN]; int dis[3 * MAXN]; void dijkstra(int s) { dis[s] = 0; priority_queue<pii, vector<pii>, greater<pii> > pq; pq.push(pii(dis[s], s)); while (pq.size()) { int cur = pq.top().second, curDis = pq.top().first; pq.pop(); if (curDis > dis[cur]) continue; for (int i = 0; i < G[cur].size(); ++i) { Node &e = G[cur][i]; if (dis[e.to] > dis[cur] + e.w) { dis[e.to] = dis[cur] + e.w; pq.push(pii(dis[e.to], e.to)); } } } } int main() { int t, n, m, c, x; for (int kase = scanf("%d", &t); kase <= t; ++kase) { scanf("%d%d%d", &n, &m, &c); for (int i = 0; i <= 3 * n; ++i) G[i].clear(), dis[i] = INF; for (int i = 1; i <= n; ++i) { scanf("%d", &x); G[i].push_back(Node(n + 2 * x, 0)); // 点和入口建边 G[n + 2 * x - 1].push_back(Node(i, 0)); // 出口和点建边 } for (int i = 1; i <= n; ++i) // 层与层间 { if (i > 1) G[n + 2 * i].push_back(Node(n + 2 * (i - 1) - 1, c)); if (i < n) G[n + 2 * i].push_back(Node(n + 2 * (i + 1) - 1, c)); } int u, v, w; for (int i = 0; i < m; ++i) { scanf("%d%d%d", &u, &v, &w); G[u].push_back(Node(v, w)); G[v].push_back(Node(u, w)); } dijkstra(1); printf("Case #%d: ", kase); if (dis == INF) puts("-1"); else printf("%d\n", dis ); } return 0; }
相关文章推荐
- Ember.js 入门指南——自定义序列号器
- MariaDB二进制安装及基本管理
- pod的安装与使用三
- Queue
- [LeetCode] Copy List with Random Pointer
- 如何在Ubuntu下打开dot文件
- POJ 1458 Common Subsequence
- cf 13a Numbers
- perl中变量的定义和使用
- POJ 1458 Common Subsequence
- 我们为什么觉得钱永远挣不完?钱永远不嫌多?
- Rectangle Area - LeetCode
- POJ 1015 Jury Compromise
- POJ 1015 Jury Compromise
- [POJ 3169]Layout[差分约束][最短路]
- cf 12a Super Agent
- 【Android成长之路】Intent初体验—使用Intent 在活动之间穿梭(一)
- eclipse转MyEclipse
- Android:带你玩转Servie,子线程,与UI线程通信[导入导出]
- 关于委托与自定义事件EventArgs浅谈