poj3255 次短路

求次短路可以利用djistra的思想变化求得。

djistra求最短路,选出一个没用被确定集合中的一个距离最短的点,去更新相连的点。而次短路一定与最短路是不同的,例如:

1——2,权值为1;则1到2的最短路为1,次短路为3。a到b的次短路,一定会经过中间点c(可能是a,b),到c的最短路加上c->b,

或到c的次短路+c->b,因此不仅要求得最短路,还要记录次短路。

对于一个点,如果更新了最短路,则先前的最短路就是次短路,如果没有,找到一条比原来次短路短,但比最短路长的,更新次短路。

最好利用优先队列。要把次短路也加入到队列中,因为可能是c的次短路+c->b。

/*
poj 3255
*/

#include 
#include 
#include 
#include 
#include 
using namespace std;
struct edge
{
	int to;
	int cost;
};
#define MAX_N 5010
std::vector v[MAX_N];
int longst[MAX_N];
int second[MAX_N];
int n,r;
#define inf 9999999
typedef pair p;
void se_path()
{
	fill(longst,longst+MAX_N,inf);
	fill(second,second+MAX_N,inf);
	priority_queue,greater

> que; que.push(p(1,0)); //longst[1]=0; while(!que.empty()) { p s=que.top(); que.pop(); int a=s.first; int b=s.second; if(second[a]d) { swap(longst[c.to],d); que.push(p(c.to,longst[c.to])); } if(second[c.to]>d && d>longst[c.to]) { second[c.to]=d; que.push(p(c.to,second[c.to])); } } } } int main(int argc, char const *argv[]) { //freopen("input","r",stdin); // freopen("output1","w",stdout); scanf("%d%d",&n,&r); for(int i=0;i



你可能感兴趣的:(图)