挑战程序设计 poj3255

白书上题

求次短路问题:

code:

#include <iostream> 
#include <algorithm> 
#include <cstdio> 
#include <cstring>
#include<cmath>
#include<cstdlib>
#include<map>
#include<string>
#include<vector>
#include<queue>
#include<functional>
#pragma warning(disable:4996)
using namespace std;
typedef long long ll;
typedef pair<int, int>P;//first是最短路径,second是顶点编号
const int INF = 0x7fffffff;


int d[100010];
int dist2[100010];
int n, r;
struct edge {
	int to, cost;
};
int V;//顶点
vector<edge>G[100010];//vectoe存图
void build_map(int r)
{
	int i, j,s,t,k;
	for (i = 1; i <=r; i++)
	{
		edge e,ee;
		scanf("%d %d %d",&s,&t,&k);
		e.to = s;  e.cost = k;
		G[t].push_back(e);
		ee.to = t; ee.cost = k;
		G[s].push_back(ee);
	}
}
void dijkstra(int s)
{
	//通过指定<greater>参数,按照first从小到大的顺序取出值
	priority_queue< P, vector<P>, greater<P> >que;
	for (int i = 1; i <= n; i++)
	{
		d[i] = INF;
		dist2[i] = INF;
	}
	d[s] = 0;//d[v]表示从起始节点到该节点的最小权值也可以说是最短路径
	que.push(P(0, s));//把起始节点存入队列g 
	//整体思想有点类似贪心
	while (!que.empty())
	{
		P p = que.top();
		que.pop();
		int v = p.second;
		if (dist2[v] < p.first)
			continue;//如果比当前此段路长 continue
		for (int i = 0; i < G[v].size(); i++)
		{
			edge e = G[v][i];
			int d2 =p.first+ e.cost;//d2可以是最短路径
			if (d[e.to] > d2)
			{
				swap(d[e.to],d2);
				que.push(P(d[e.to], e.to));
			}
			if (dist2[e.to] > d2&&d[e.to]<d2)//保证次短路是小于最短路的
			{
				dist2[e.to] = d2;
				que.push( P(dist2[e.to], e.to) );
			}
		}
	}
	
}
int main()
{
		scanf("%d %d", &n, &r);
		for (int i = 1; i <= n; i++)
			G[i].clear();
		build_map(r);
		dijkstra(1);
		printf("%d\n", dist2[n]);
	return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值