题解 | #最短路径问题#

最短路径问题

https://www.nowcoder.com/practice/e372b623d0874ce2915c663d881a3ff2

#include<iostream>
#include<queue>
#include<map>
#include<string>
#include<vector>

using namespace std;

const int MAXN = 1e3+500;
const int INF = 1e6;
int N, M;


struct  Edge
{
	int U,V,WEIGHT, COST;
	Edge(int a, int b, int d, int p)
	{
		U = a, V = b, WEIGHT = d, COST = p;
	}
};
struct Node
{
	int index, dis;
	Node(int a, int  b)
	{
		index = a, dis = b;
	}
	friend bool operator<(Node a,Node b)
	{
		return a.dis > b.dis;
	}
};
vector<Edge>Adj[MAXN];

int dist[MAXN];
int cost[MAXN];
void initconfig()
{
	for (int i = 0; i < MAXN; i++)
	{
		Adj[i].clear();
	}
	fill(dist, dist + MAXN, INF);
	fill(cost, cost + MAXN, INF);
}

void Dijstra(int start_index,int taget_index)
{
	priority_queue<Node>q;
	dist[start_index] = 0;
	cost[start_index] = 0;
	q.push(Node(start_index, dist[start_index]));
	while (q.empty()==false)
	{
		Node top = q.top(); q.pop();
		for (int i = 0; i < Adj[top.index].size(); i++)
		{
			Edge e = Adj[top.index][i];
			bool flag1 = dist[e.V]> dist[e.U] + e.WEIGHT;
			bool flag2 = (dist[e.V] == dist[e.U] + e.WEIGHT) && (cost[e.V] > cost[e.U]+ e.COST);
			if (flag1||flag2)
			{
				dist[e.V] = dist[e.U] + e.WEIGHT;
				cost[e.V] = cost[e.U] + e.COST;
				q.push(Node(e.V, dist[e.V]));
			}
		}
	}
}

int main()
{
	initconfig();
	scanf("%d %d", &N, &M);
	for (int i = 0; i < M; i++)
	{
		int a, b, d, p;
		scanf("%d %d %d %d", &a, &b, &d, &p);
		Adj[a].push_back(Edge(a, b, d, p));
		Adj[b].push_back(Edge(b, a, d, p));
	}
	int s, t;
	scanf("%d %d", &s, &t);
	Dijstra(s,t);
	cout << dist[t] << " " << cost[t] << endl;

}

全部评论

相关推荐

点赞 评论 收藏
分享
05-21 15:47
门头沟学院 Java
浪漫主义的虹夏:项目有亮点吗,第一个不是纯玩具项目吗,项目亮点里类似ThreadLocal,Redis储存说难听点是花几十分钟绝大部分人都能学会,第二个轮子项目也没体现出设计和技术,想实习先沉淀,好高骛远的自嗨只会害了自己
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-07 13:35
虽然不怎么光彩,经过这件事,可能我真的要去认同“面试八股文早该淘汰!不会用AI作弊的程序员=新时代文盲!”这句话了
HellowordX:Ai的出现是解放劳动力的,不是用来破坏公平竞争环境的,这样下去,轻则取消所有线上面试,严重了会影响整个行业对所有人产生影响,企业会拉高入职考核各种离谱考核会层出不穷
你找工作的时候用AI吗?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务