POJ2387 奶牛回家(dijkstra)

版权声明:版权所有,转载请标明 https://blog.csdn.net/zxwsbg/article/details/79432968

每日打卡(2/2)

传送门:点击打开链接

题目大意:

    给定起点终点,求最短路

解法:

    用优先队列的dijkstra。

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
#include<string>
#include<vector>
using namespace std;
const int maxn = 1005;

vector<pair<int,int> >E[maxn];
int t,n,d[maxn];

void init()
{
	for(int i=0;i<maxn;i++)
	{
		d[i] = 1e9;
		E[i].clear();
	}
}

int main()
{
	cin>>t>>n;
	init();
	while(t--)
	{
		int x,y,z;
		cin>>x>>y>>z;
		E[x].push_back(make_pair(y,z));
		E[y].push_back(make_pair(x,z));
	}
	int s,e;
	s = 1,e = n;
	d[s] = 0;
	priority_queue<pair<int,int> >q;
	q.push(make_pair(-d[s],s));
	while(!q.empty())
	{
		int now = q.top().second;
		q.pop();
		for(int i=0;i<E[now].size();i++)
		{
			int v = E[now][i].first;
			if(d[v]>d[now]+E[now][i].second)
			{
				d[v] = d[now]+E[now][i].second;
				q.push(make_pair(-d[v],v));
			}
		}
	}
	cout<<d[e]<<endl;
	return 0;
}

没有更多推荐了,返回首页