POJ 3255 Roadblocks 次短路

题目链接:点击打开链接

题意:一个无向图,求从起点到终点的最短路(可以重复走),

思路:从分别以起点和原点做最短路,然后求枚举每条边,求出比最短路长的最短的哪一条.

cpp:点击打开链接

#include <cmath>
#include <iostream>
#include <map>
#include <vector>
#include <cstring>
#include <queue>
#include <cstdio>
#include <algorithm>
using namespace std;
const int INF=1e9;
const int maxn=10010;
struct Edge{
	int from,to,dist;
	Edge(int u,int v,int d):from(u),to(v),dist(d) {}
};

struct HeapNode{
	int d,u;
	bool operator < (const HeapNode& rhs) const{
		return d > rhs.d;
	}
};
struct Dijkstra{
	int n,m;
	vector<Edge> edges;
	vector<int> G[maxn];
	bool done[maxn];
	int d[maxn];
	
	void init(int n)
	{
		this->n=n;
		for(int i=0;i<n;i++) G[i].clear();
		edges.clear();
	}
	
	void addEdges(int from,int to,int dist)
	{
		edges.push_back(Edge(from,to,dist));
		m=edges.size();
		G[from].push_back(m-1);
	}
	
	
	
	void dijkstra(int s)
	{
		priority_queue<HeapNode> Q;
		for(int i=0;i<n;i++) d[i]=INF;
		d[s]=0;
		memset(done,0,sizeof(done));
		HeapNode tep;
		tep.d=0,tep.u=s;
		Q.push(tep);
		while (!Q.empty())
		{
			HeapNode x=Q.top();Q.pop();
			int u=x.u;
			if(done[u]) continue;
			done[u]=true;
			for(int i=0;i<G[u].size();i++)
			{
				Edge& e=edges[G[u][i]];
				if(d[e.to]>d[u]+e.dist)
				{
					d[e.to]=d[u]+e.dist;
					tep.d=d[e.to],tep.u=e.to;
					Q.push(tep);
				}
			}
		}
	}
	
	
};




Dijkstra dij1,dij2;
int main ()
{
	int ans;
	int tp,a,b,n,m;
	int temp;
	//freopen("data.in","r",stdin);
    while (~scanf("%d%d",&n,&m))
    {
		dij1.init(n);
		dij2.init(n);
        for (int i=1;i<=m;i++)
        {
            scanf("%d%d%d",&a,&b,&tp);
			dij1.addEdges(a-1,b-1,tp);
			dij2.addEdges(b-1,a-1,tp);
			dij2.addEdges(a-1,b-1,tp);
			dij1.addEdges(b-1,a-1,tp);
        }
		dij1.dijkstra(0);
		dij2.dijkstra(n-1);
        ans=INF;
		for(int i=0;i<dij1.edges.size();i++)
		{
			Edge tem=dij1.edges[i];
			
			temp=dij1.d[tem.from]+dij2.d[tem.to]+tem.dist;
			if(temp==dij1.d[n-1])
			{
				temp+=2*tem.dist;
			}
			ans=min(ans,temp);
		}
		cout<<ans<<endl;
    }
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值