POJ3255

10 篇文章 0 订阅

求次短路,先求出1到所有点的距离dist,再求出N到所有点的距离dist[1],然后遍历所有边 dist[u]+cost[u][v]+dist1[v]第二的就是次短路。

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<utility>
#include<string.h>
#include<queue>
#include<vector>
using namespace std;

const int INF=0x3f3f3f3f;

typedef pair<int,int> P; 

struct edge
{
	int to;
	int cost;
}e[300003];

vector<edge> G[6002];

int dist[6002];
int dist2[6002];
int ans[200003];
priority_queue < P, vector<P> , greater<P> > q;

int i,j,k;

void dij(int s,int * d)
{
	while(!q.empty())
		q.pop();
	for(i=0;i<5001;i++)
		d[i]=INF;
	d[s]=0;
	q.push(P(0,s));
	P tp;
	int f;
	while(!q.empty())
	{
		tp=q.top();
		q.pop();
		f=tp.second;
		if(d[f]<tp.first)
			continue;
		for(i=0;i<G[f].size();i++)
		{
			edge &te=G[f][i];
			if(d[te.to]>d[f]+te.cost)
			{
				d[te.to]=d[f]+te.cost;
				q.push(P(d[te.to],te.to));
			}
		}
	}
}
int main()
{
	int n,r,f;
	scanf("%d%d",&n,&r);
	for(i=0;i<r;i++)
	{
		scanf("%d%d%d",&f,&e[i].to,&e[i].cost);
		G[f].push_back(e[i]);
		e[i+r].to=f;
		e[i+r].cost=e[i].cost;
		G[e[i].to].push_back(e[i+r]);	
	}
	dij(1,dist);
	dij(n,dist2);
	k=0;
	for(i=1;i<=n;i++)
	{
		for(j=0;j<G[i].size();j++)
		{
			edge &te=G[i][j];
			ans[k++]=dist[i]+te.cost+dist2[te.to];
		}
	}
	sort(ans,ans+k);
	int st=ans[0];
	for(i=0;ans[i]==st;i++);
	printf("%d\n",ans[i]);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值