1486E - Paired Payment
题意
给定一个不保证连通的无向图,每次走都必须连着走两条路( a , b , c a, b, c a,b,c 三个点,则只能走 a b — b c ab—bc ab—bc 到 c c c ,或者 a c — c b ac—cb ac—cb 到 b b b ),且所花费的金钱为两条路的边权和的平方( ( w a b + w b c ) 2 (w_{ab} + w_{bc})^2 (wab+wbc)2 )。问从第一个点到其他所有点花费的最小金额各是多少?没有路径输出-1。
思路
参考:
E. Paired Payment(多维最短路dijkstra)
Codeforces-1486 E. Paired Payment(多维最短路
普通的dijtra是用 cost[v]
表示起点到点
v
v
v 的最短路径(这题问的是价格,就用cost来呼应了),原来的转移方程式为:
if(cost[nxt.v] > nxt.w + now.w){
cost[nxt.v] = nxt.w + now.w;//松弛
que.push(nxt.v, cost[nxt.v]);//加入队列
}
这里我们用 cost[v][w][num]
表示从起点到点
v
v
v ,上一个点的边权是
w
w
w ,此时一共经过了
n
u
m
num
num 个点。因为
n
u
m
num
num 对答案的影响只是在于其奇偶性(奇数个需要计算上一个点边权+当前点边权和的平方,偶数个不需要),所以
n
u
m
num
num 的取值可以压缩为0,1。现在的转移方程式变为:
co = now.num ? (now.w + nxt.w) * (now.w + nxt.w) : 0;//是否需要加上权值
if(cost[nxt.v][nxt.w][now.num ^ 1] > cost[now.v][now.w][now.num] + co){
cost[nxt.v][nxt.w][now.num ^ 1] = cost[now.v][now.w][now.num] + co;
que.push({nxt.v,
nxt.w,
cost[nxt.v][nxt.w][now.num ^ 1],
now.num ^ 1});
}
其主要的思路就是让数组 cost
存储更多的信息。
代码
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define PI acos(-1)
using namespace std;
typedef pair<int, int> P;
typedef long long ll;
const int N = 1e5 + 19;
const ll mod = 1e9 + 7;
struct edge
{
ll v, w;
edge() {}
edge(ll vv, ll ww)
{
v = vv;
w = ww;
}
};
struct node
{
ll v, w, sum, num;
bool operator < (const node& a) const
{
return sum > a.sum;
}
};
vector<edge> es[N];
priority_queue<node> que;
ll cost[N][55][3];
int n, m;
void addEdge(int u, int v, int w)
{
es[u].push_back(edge(v, w));
es[v].push_back(edge(u, w));
}
void dij(int s)
{
memset(cost, INF, sizeof(cost));
cost[s][0][0] = 0;
que.push({s, 0, 0, 0});
while(!que.empty())
{
node now = que.top();
que.pop();
for(int i = 0; i < es[now.v].size(); i++)
{
edge nxt = es[now.v][i];
ll co = now.num ? (now.w + nxt.w) * (now.w + nxt.w) : 0;
if(cost[nxt.v][nxt.w][now.num ^ 1] > cost[now.v][now.w][now.num] + co)
{
cost[nxt.v][nxt.w][now.num ^ 1] = cost[now.v][now.w][now.num] + co;
que.push({nxt.v,
nxt.w,
cost[nxt.v][nxt.w][now.num ^ 1],
now.num ^ 1});
}
}
}
}
int main()
{
cin >> n >> m;
for(int i = 0, u, v, w; i < m; i++)
{
cin >> u >> v >> w;
addEdge(u, v, w);
}
dij(1);
for(int i = 1; i <= n; i++)
{
ll ans = INF;
for(int j = 0; j <= 50; j++)
ans = min(ans, cost[i][j][0]);
if(ans == INF)
{
cout << -1 << ' ';
continue;
}
cout << ans << ' ';
}
cout << endl;
return 0;
}