Title:
Given a weighted undirected graph, two edges must be walked at a time, and the cost is (w 1 + w 2) 2 (w_1+w_2)^2(w1+w2)2. Find the shortest path from 1 to each point.
answer:
The breakthrough point of this question is the edge weight, because the size of the edge weight is only 50, so it can be used in dijkstra dijkstraMake a little change on d i j k s t r a to change the original one-dimensionaldis disThe d i s array is changed to three-dimensional, and more states are recorded in the structure,dis [i] [j] [odd] dis[i][j][odd]d i s [ i ] [ j ] [ o d d ] means that the passing edge weight isjjthe edge of j reaches pointiithe shortest path of i ,odd oddo d d means pointiiIs i the middle point of the two sides?
Then the rest is to run dijkstra dijkstraJust d i j k s t r a .
Code:
#include<bits/stdc++.h>
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
#include<map>
#include<stack>
#include<set>
#include<ctime>
#define iss ios::sync_with_stdio(false)
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int,int>pii;
const int MAXN=1e5+5;
const int mod=1e9+7;
const int inf=0x3f3f3f3f;
int head[MAXN];
int vis[MAXN][55][2];
ll dis[MAXN][55][2];
int cnt;
struct edge
{
int to;
int cost;
int next;
}e[MAXN*4];
struct node
{
int pos,w,odd;
ll val;
node(int pos,int w,int odd,ll val)
{
this->pos=pos;
this->w=w;
this->odd=odd;
this->val=val;
}
friend bool operator<(node a,node b)
{
return a.val>b.val;
}
};
void add(int u,int v,int w)
{
e[cnt].to=v;
e[cnt].cost=w;
e[cnt].next=head[u];
head[u]=cnt++;
}
void solve(int s)
{
memset(vis,0,sizeof vis);
memset(dis,inf,sizeof dis);
priority_queue<node> q;
q.push(node{
s,0,0,0});
dis[s][0][0]=0;
while(!q.empty())
{
node now=q.top();
q.pop();
if(vis[now.pos][now.w][now.odd]) continue;
vis[now.pos][now.w][now.odd]=1;
for(int i=head[now.pos];i!=-1;i=e[i].next)
{
int v=e[i].to;
ll cost;
if(now.odd==1) cost=(now.w+e[i].cost)*(now.w+e[i].cost);
if(now.odd==1&&dis[v][e[i].cost][0]>now.val+cost)
{
dis[v][e[i].cost][0]=now.val+cost;
q.push(node{
v,e[i].cost,0,now.val+cost});
}
else if(now.odd==0&&dis[v][e[i].cost][1]>now.val)
{
dis[v][e[i].cost][1]=now.val;
q.push(node{
v,e[i].cost,1,now.val});
}
}
}
}
int main()
{
memset(head,-1,sizeof head);
int n,m;
cin>>n>>m;
for(int i=1;i<=m;i++)
{
int u,v,w;
cin>>u>>v>>w;
add(u,v,w);
add(v,u,w);
}
solve(1);
for(int i=1;i<=n;i++)
{
ll ans=inf;
for(int j=0;j<=50;j++)
{
ans=min(ans,dis[i][j][0]);
}
if(ans<inf) printf("%lld ",ans);
else printf("-1 ");
}
}