题目:E. Paired Payment
分析:
定义dis[i][j][k]表示从起点到i点的路径的最后一条边权值为j且经过的边数是奇数(k=1)时的最短路,只有从k=1转移到k=0时,转移才加cost。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;//三年竞赛一场空,不开long long见祖宗
//typedef __int128 lll;
#define print(i) cout << "debug: " << i << endl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
#define pb(a) push_back(a)
#define x first
#define y second
typedef pair<int, int> pii;
const double eps = 1e-8;
const ll mod = 1e9 + 7;
const int maxn = 2e5 + 10;
const ll inf = 0x3f3f3f3f3f3f3f3f;
struct edge
{
int ep, val, nex;
}e[maxn << 1];
int head[maxn], tot;
void init()
{
mem(head, -1), tot = 0;
}
void add(int x, int y, int val)
{
e[tot] = {y, val, head[x]}, head[x] = tot++;
}
struct node
{
int id, lastval, odd;
ll v;
bool operator < (const node &b)const{
return b.v < v;
}
};
ll dis[maxn][52][2];
int vis[maxn][52][2];
int n, m;
void dj()
{
mem(dis, 0x3f); mem(vis, 0);
dis[1][0][0] = 0;
priority_queue<node> q; q.push({1, 0, 0, 0});
while(!q.empty())
{
node now = q.top(); q.pop();
int id = now.id, lastval = now.lastval, odd = now.odd;
ll nowdis = now.v;
if(vis[id][lastval][odd]) continue;
vis[id][lastval][odd] = 1;
for(int i = head[id]; ~i; i = e[i].nex)
{
ll cost = 0;
if(odd) cost = (lastval + e[i].val) * (lastval + e[i].val);
int ep = e[i].ep;
if(dis[ep][e[i].val][odd ^ 1] > dis[id][lastval][odd] + cost)
{
dis[ep][e[i].val][odd ^ 1] = dis[id][lastval][odd] + cost;
q.push({ep, e[i].val, odd ^ 1, dis[ep][e[i].val][odd ^ 1]});
}
}
}
}
int main()
{
init();
cin >> n >> m;
for(int i = 1; i <= m; i++)
{
int x, y, val; cin >> x >> y >> val;
add(x, y, val), add(y, x, val);
}
dj();
for(int i = 1; i <= n; i++)
{
ll minn = inf;
for(int j = 0; j <= 50; j++)
minn = min(minn, dis[i][j][0]);
printf("%lld%c", minn == inf ? -1 : minn, i == n ? '\n' : ' ');
}
}