题解 | #最短路径问题#

最短路径问题

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;

}

全部评论

相关推荐

半解316:内容充实,细节需要修改一下。 1,整体压缩为一页。所有内容顶格。 2,项目描述删除,直接写个人工作量 修改完之后还需要建议,可以私聊
点赞 评论 收藏
分享
Twilight_m...:经典我朋友XXXX起手,这是那种经典的不知道目前行情搁那儿胡编乱造瞎指导的中年人,不用理这种**
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-03 18:22
投了几百份简历,专业和方向完全对口,都已读不回。尝试改了一下学校,果然有奇效。
steelhead:这不是很正常嘛,BOSS好的是即便是你学院本可能都会和聊几句,牛客上学院本机会很少了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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