LOJ1099来回次短路

思路:求从S->T的次短路,不同的是,每条路是可以重复走的;那么在更新的时候就要注意下了;

可以设dis[i][0] 是S->i 的当前最短路,dis[i][1]是S->i的当前次短路;然后用优先队列维护这个性质;

typedef pair<int,int> ii;

queue<ii> que;//小的优先

node u = que.top();

que.pop();

u.first + w<a,b> 可以更新S->i的当前最短路权的话,也能改变S->i的当前次短路权,同时更新,然后加入队列;

u.first + w<a,b> 只能更新当前次短的话,就只更新次短,然后介入队列;

题目链接

/*****************************************
Author      :Crazy_AC(JamesQi)
Time        :
File Name   :
*****************************************/
#include <iostream>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <limits.h>
using namespace std;
#define FILL(a,b) memset(a,b,sizeof a)
#define CLR(a) memset(a,0,sizeof a)
#define mk make_pair
template<class T> inline T Get_Max(const T&a,const T&b) {return a < b?b:a;}
template<class T> inline T Get_Min(const T&a,const T&b) {return a < b?a:b;}

const int inf = 0x3f3f3f3f;
const int maxn = 5555;
const int maxm = 555555;
struct Edge{
	int to,w,next;
	Edge(int a = 0,int b = 0,int c = 0)
	{
		to = a;
		w = b;
		next = c;
	}
}E[maxm];
typedef pair<int,int> ii;
int head[maxn],n,m,e_cnt;


int dis[maxn],length[maxn];//最短,次短


inline void Add_Edge(int u,int v,int w)
{
	E[e_cnt].to = v;
	E[e_cnt].w = w;
	E[e_cnt].next = head[u];
	head[u] = e_cnt++;
}

int Dijkstra()
{
	FILL(dis,inf);
	FILL(length,inf);
	priority_queue<ii,vector<ii>,greater<ii> > que;
	que.push(mk(0,1));
	dis[1] = 0;
	while(!que.empty())
	{
		ii tmp = que.top();
		que.pop();
		int u = tmp.second;
		// cout << "dis = " << dis[u] << endl;
		for (int i = head[u];i != -1;i = E[i].next)
		{
			int v = E[i].to;
			int w = E[i].w;
			if (dis[v] > tmp.first + w)
			{
				length[v] = dis[v];
				// cout << "length = " << length[v] << endl;
				dis[v] = w + tmp.first;
				que.push(mk(dis[v],v));
			}
			else if (dis[v] != tmp.first + w && tmp.first + w < length[v])
			{
				length[v] = tmp.first + w;
				que.push(mk(length[v],v));//提供了更新次短路的可能性->重复走;
			}
			// printf("length[%d] = %d\n",v,length[v]);
		}
	}
	return length[n];
}


int main()
{
	// freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	int iCase = 0;
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%d",&n,&m);
		e_cnt = 0;
		FILL(head,-1);
		while(m--)
		{
			int u,v,w;
			scanf("%d%d%d",&u,&v,&w);
			Add_Edge(u,v,w);
			Add_Edge(v,u,w);
		}
		printf("Case %d: %d\n",++iCase,Dijkstra());
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值