[图初学之dijkstra] HDU 2066

初学堆优化的dijkstra算法,正好有道模板题HDU 2066,随便写了一下没想到过了,WA了一次还是上次的毛病,用邻接表构建无向图时没有连两遍。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <queue>

using namespace std;

const int INF=100000000;

struct edge {int to,cost;};
typedef pair<int,int> P;//first是距离,second是ds里的下标

std::vector<edge> G[1001];
int ds[1001];//最短距离


void dijkstra(int s)
{
	priority_queue<P, std::vector<P>, greater<P> > que;//按距离从小到大取出元素的堆

	ds[s]=0;
	que.push(P(0,s));

	while(!que.empty())
	{
		P p=que.top();//堆顶元素,为还未计算的距离中的最短距离
		que.pop();
		int v=p.second;
		if(ds[v]<p.first)
			continue;
		for (int i = 0; i < G[v].size(); ++i)
		{
			edge e=G[v][i];
			if (ds[e.to]>ds[v]+e.cost)
			{
				ds[e.to]=ds[v]+e.cost;
				que.push(P(ds[e.to],e.to));
			}
		}
	}
}


int main(int argc, char const *argv[])
{
	int t,s,d;
	while(scanf("%d%d%d",&t,&s,&d)!=EOF)
	{
		fill(ds,ds+1001,INF);
		ds[0]=0;
		for (int i = 0; i < 1001; ++i)
			G[i].clear();

		while(t--)
		{
			int a,b,time;
			scanf("%d%d%d",&a,&b,&time);
			edge tem;
			tem.to=b;
			tem.cost=time;
			G[a].push_back(tem);
			tem.to=a;
			G[b].push_back(tem);//无向图注意连两遍
		}

		while(s--)
		{
			int dir;
			scanf("%d",&dir);
			edge tem;
			tem.to=dir;
			tem.cost=0;
			G[0].push_back(tem);
		}

		dijkstra(0);

		int ans=INF;
		while(d--)
		{
			int des;
			scanf("%d",&des);
			if(ds[des]<ans)
				ans=ds[des];
		}
		printf("%d\n",ans);

	}

	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值