CodeForces 1486E Paired Payment (最短路变形)(Dijkstra)

题目大意
一个无向图,有n 个点和 m 条边,每条边的权值为 w.
规定,每次要走两个节点,代价为 (Vala + Valb) 2.
输出到达每个点的最小代价,如果无法到达就输出 -1.

思路
很明显,和最短路的模板题相比,我们需要多记录一条边。
观察发现,这个题内边的权值较小,我们可以用边权作为一个维度来记录多出来的一个边。
dis[0][x] 表示第二条边到达 x 点的最小代价,这也就是 x 点对应的答案
dis[w][x] 表示通过边权 w 的边到达 x 点的最小代价。

细节看代码。

代码


#include <bits/stdc++.h>
#include <vector>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
#include <set>
#include <stack>
#define ll long long
#define chushi(a, b) memset(a, b, sizeof(a))
#define endl "\n"
const double eps = 1e-8;
const ll INF=0x3f3f3f3f3f3f3f3f;
const ll mod = 998244353;
const int maxn = 2e5 + 5;

using namespace std;

typedef struct Node{
	int u;
	int v;
	int w;
	bool operator < (const Node &a)const{	// 重载小于号 
		return w > a.w;
	}
} node;

vector<node> ma[maxn];		// 存图 

priority_queue<node> qu;	// 优先队列 

bool vis[55][maxn];	// 标记状态是否达到过 
int dis[55][maxn];	// 记录代价 

void dij(int n){
	for(int i = 1; i <= n; i++){
		for(int j = 0; j <= 50; j++){
			dis[j][i] = 1e9;	// 初始化 
		}
	}
	
	qu.push({1, 0, 0});
	dis[0][1] = 0;	// 到达第一个点 前驱边的权值为 0 
	
	while(!qu.empty()){
		node now = qu.top(); // now 中 u表示当前点, v表示前驱权值, w表示当前权值 
		qu.pop();
						
		if(vis[now.v][now.u]) continue;
		vis[now.v][now.u] = 1;
		
		int len = ma[now.u].size();
		for(int i = 0; i < len; i++){
			node next = ma[now.u][i];	// next 中 u表示当前点, v表示要达到的点, w表示这个边的权值 
			if(now.v == 0){	// 前驱权值为 0,说明接下来是要走第一条边 
				int w = now.w + next.w;
				if(w < dis[next.w][next.v]){
					dis[next.w][next.v] = w;
					qu.push({next.v, next.w, w});
				}
			}
			else{			// 前驱权值不为 0,说明接下来是要走第二条边 
				int w = now.w - now.v + (next.w + now.v) * (next.w + now.v);
				if(w < dis[0][next.v]){
					dis[0][next.v] = w;
					qu.push({next.v, 0, w});
				}
			}
		}
	}
	
}

int main(){
	
	int n, m;
	cin >> n >> m;
	int u, v, w;
	for(int i = 1; i <= m; i++){
		cin >> u >> v >> w;
		ma[u].push_back({u, v, w});	
		ma[v].push_back({v, u, w});
	}
	
	dij(n);
	
	for(int i = 1; i <= n; i++){
		if(1e9 == dis[0][i]) cout << "-1 ";
		else cout << dis[0][i] << " ";
	}
	cout << endl;
	
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值