bzoj 1726: [Usaco2006 Nov]Roadblocks第二短路【dijskstra】

严格次短路模板,用两个数组分别维护最短路和次短路,用dijskstra,每次更新的时候先更新最短路再更新次短路
写了spfa版的不知道为啥不对……

#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int N=5005,inf=1e9;
int n,m,h[N],cnt,d1[N],d2[N];
struct qwe
{
	int ne,to,va;
}e[200005];
int read()
{
    int r=0,f=1;
    char p=getchar();
    while(p>'9'||p<'0')
    {
        if(p=='-')
            f=-1;
        p=getchar();
    }
    while(p>='0'&&p<='9')
    {
        r=r*10+p-48;
        p=getchar();
    }
    return r*f;
}
void add(int u,int v,int w)
{
	cnt++;
	e[cnt].ne=h[u];
	e[cnt].to=v;
	e[cnt].va=w;
	h[u]=cnt;
}
int main()
{
	n=read(),m=read();
	for(int i=1;i<=m;i++)
	{
		int x=read(),y=read(),z=read();
		add(x,y,z),add(y,x,z);
	}
	priority_queue<pair<int,int>,vector<pair<int,int> >,greater<pair<int,int> > >q;
	for(int i=1;i<=n;i++)
		d1[i]=d2[i]=inf;
	d1[1]=0;
	q.push(make_pair(0,1));
	while(!q.empty())
	{
		int w=q.top().first,u=q.top().second;
		q.pop();
		if(w>d2[u])
			continue;
		for(int i=h[u];i;i=e[i].ne)
		{
			int d=w+e[i].va;
			if(d1[e[i].to]>d)
			{
				swap(d1[e[i].to],d);
				q.push(make_pair(d1[e[i].to],e[i].to));
			}
			if(d1[e[i].to]<d&&d2[e[i].to]>d)
			{
				d2[e[i].to]=d;
				q.push(make_pair(d2[e[i].to],e[i].to));
			}
		}
	}
	printf("%d\n",d2[n]);
	return 0;
}
posted @ 2018-04-28 21:39  lokiii  阅读(182)  评论(0编辑  收藏  举报