题目链接
https://codeforces.com/contest/1486/problem/E
思路
题意是给定一个n个点m条边的无向图,保证没有重边,但是你必须一次走两条边,途中经过的点只是路过不算抵达,抵达的点所需要的的花费是这两条边的和的平方,题目规定点的编号是1-n,起点规定是1号点,要求输出1号点到所有点的(包括自己)的最小花费,如果不能抵达则输出-1.
这题首先不能暴力重新建图会O(n²),这题我搜到的第一个题解是利用hash映射虚拟点dij,老实说我觉得很nb,但是我太菜了还没能理解,第二篇题解让我差不多明白他的做法,很简单,在经典dist数组的基础上添加了两维,一维是上一层的边权,一层是状态,奇数1表示只是经过,偶数0表示是抵达,然后再用堆优化dij来做,(代码中间要用到优先队列,所以建立的结构体内部要重载一下小于号)
代码
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 1e5+10 , inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
int n,m;
int h[N],idx;
ll dist[N][51][2];
struct edge
{
int to,ne,w;
}e[N<<2];
struct node
{
ll len;
int pos,last,odd;
friend bool operator<(node a,node b)
{
return a.len>b.len;
}
};
void add(int a,int b,int w)
{
e[++idx]={b,h[a],w};
h[a]=idx;
}
void dij()
{
priority_queue<node>q;
memset(dist,0x3f,sizeof(dist));
dist[1][0][0]=0;
q.push({0,1,0,0});
while(q.size())
{
auto t=q.top();
q.pop();
ll len=t.len;
int pos=t.pos;
int last=t.last;
int odd=t.odd;
if(len!=dist[pos][last][odd]) continue;
for(int i=h[pos];i!=-1;i=e[i].ne)
{
int to=e[i].to;
int w=e[i].w;
if(!odd)
{
if(dist[to][w][odd^1]>dist[pos][last][odd])
{
dist[to][w][odd^1]=dist[pos][last][odd];
q.push({dist[to][w][odd^1],to,w,odd^1});
}
}
else
{
if(dist[to][w][odd^1]>dist[pos][last][odd]+(last+w)*(last+w))
{
dist[to][w][odd^1]=dist[pos][last][odd]+(last+w)*(last+w);
q.push({dist[to][w][odd^1],to,w,odd^1});
}
}
}
}
}
int main()
{
scanf("%d%d",&n,&m);
memset(h,-1,sizeof(h));
for(int i=0;i<m;i++)
{
int a,b,w;
scanf("%d%d%d",&a,&b,&w);
add(a,b,w);
add(b,a,w);
}
dij();
for(int i=1;i<=n;i++)
{
ll mi=INF;
for(int j=0;j<=50;j++)
{
mi=min(mi,dist[i][j][0]);
}
if(mi==INF) mi=-1;
printf("%lld ",mi);
}
puts("");
}