您的位置:首页 > 其它

[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。

个人感受:

果然图见多了才有感觉,学习了~

具体代码如下:

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: