题意:
给一张无向图,求从1到n的次短路。
解析:
A* + spfa 或者 dijkstra。
详解见上一题:http://blog.csdn.net/u013508213/article/details/46400189
本题,spfa中,stack超时,queue的效率最高,priority_queue次之。
代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <map>
#include <climits>
#include <cassert>
#define LL long long
#define lson lo, mi, rt << 1
#define rson mi + 1, hi, rt << 1 | 1
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 5000 + 1;
const int maxm = 100000 + 1;
int n, m;
int st, ed;
int edgeNum;
int head[maxn];
struct Edge
{
int to, cost, nxt;
} e[maxm << 1];
void initEdge()
{
memset(head, -1, sizeof(head));
edgeNum = 0;
}
void addEdge(int fr, int to, int cost)
{
e[edgeNum].to = to;
e[edgeNum].cost = cost;
e[edgeNum].nxt = head[fr];
head[fr] = edgeNum++;
}
int dis[maxn];
bool vis[maxn];
///stack TLE queue AC priority_queue AC
void spfa()
{
for (int i = 1; i <= n; i++)
{
dis[i] = inf;
vis[i] = false;
}
priority_queue<int> q;
q.push(ed);
vis[ed] = true;
dis[ed] = 0;
while (!q.empty())
{
int cur = q.top();
q.pop();
for (int i = head[cur]; i != -1; i = e[i].nxt)
{
int x = e[i].to;
if (dis[cur] + e[i].cost < dis[x])
{
dis[x] = dis[cur] + e[i].cost;
if (!vis[x])
{
vis[x] = true;
q.push(x);
}
}
}
vis[cur] = false;
}
}
//void dij()
//{
// int i,j,k;
// bool vis[maxn];
// memset (vis,false,sizeof(vis));
// memset (dis,0x3f,sizeof(dis));
// dis[ed] = 0;
// for (i = 1; i <= n; i ++)
// {
// int min = inf;
// for (j = 1; j <= n; j ++)
// if (!vis[j]&&dis[j] < min)
// {
// min = dis[j];
// k = j;
// }
// vis[k] = true;
// for (int u = head[k]; u != -1; u = e[u].nxt)
// {
// int v = e[u].to;
// if (!vis[v]&&dis[v] > dis[k] + e[u].cost)
// dis[v] = dis[k] + e[u].cost;
// }
// }
//}
struct Node
{
int pos;
int h, g;
bool operator < (const Node a) const
{
return a.h + a.g < h + g;
}
};
int Astar(int k)
{
int cnt = 0;
if (st == ed)
k++;
if (dis[st] == inf)
return -1;
priority_queue<Node> q;
Node now, nxt;
now.pos = st, now.g = 0, now.h = dis[st];
q.push(now);
while (!q.empty())
{
nxt = q.top();
q.pop();
if (nxt.pos == ed)
{
cnt++;
if (cnt == k)
return nxt.g;
}
for (int i = head[nxt.pos]; i != -1; i = e[i].nxt)
{
now.pos = e[i].to;
now.g = nxt.g + e[i].cost;
now.h = dis[e[i].to];
q.push(now);
}
}
return 0;
}
int main()
{
#ifdef LOCAL
freopen("in.txt", "r", stdin);
#endif // LOCAL
while (~scanf("%d%d", &n, &m))
{
initEdge();
while (m--)
{
int fr, to, cost;
scanf("%d%d%d", &fr, &to, &cost);
addEdge(fr, to, cost);
addEdge(to, fr, cost);
}
st = 1;
ed = n;
spfa();
// dij();
printf("%d\n", Astar(2));
}
return 0;
}