您的位置:首页 > 其它

Roadblocks--poj3255(次短路)

2015-08-06 09:12 253 查看
题目链接

求次短路的问题;

dist[i][0]和dist[i][1]表示从起点1到i的距离和从起点n到i的距离;

次短路要比最短路大但小于其他路;

每条路1--n的距离都可以用dist[i][0] + dist[j][1] + G[j].w表示;、、具体的可以仔细想想;


#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <cstring>
using namespace std;
#define INF 0xfffffff
#define N 5060

struct Edge
{
int e,w;
Edge(int x=0, int y=0):e(x),w(y){}
};

vector<Edge> G
;
int dist
[2], n, m, vis
;

void spfa(int s, int k)
{
queue<Edge>Q;
Edge p, q;
dist[s][k] = 0;
Q.push(Edge(s, 0));
while(Q.size())
{
p=Q.front(); Q.pop();
vis[p.e] = 1;
int len = G[p.e].size();
for(int i=0; i<len; i++)
{
q = G[p.e][i];
if(dist[q.e][k] > dist[p.e][k] + q.w)
{
dist[q.e][k] = dist[p.e][k] + q.w;
if(vis[q.e] == 0)
{
Q.push(q);
vis[q.e] = 1;
}
}
}
}

}

int main()
{
int a, b, c;
while(scanf("%d%d", &n, &m)!=EOF)
{
for(int i=0;i<=n;i++)
{
G[i].clear();
dist[i][0]= dist[i][1]=INF;

}
for(int i=0; i<m;i++)
{
scanf("%d%d%d", &a, &b, &c);
G[a].push_back(Edge(b, c));
G[b].push_back(Edge(a, c));
}
spfa(1, 0);
spfa(n, 1);

int ans = INF;
for(int i=1; i<=n; i++)
{
int len = G[i].size();
for(int j=0; j<len; j++)
{
int W=G[i][j].w + dist[i][0] +dist[G[i][j].e][1];
if(ans>W && W>dist
[0])
{
ans=W;
}
}
}
printf("%d\n", ans);

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