Codeforces Round #703 (Div. 2) E. Paired Payment(最短路)

题意:

给出一个带权无向图,一次必须走两条边,花费为 ( w 1 + w 2 ) 2 (w_1+w_2)^2 (w1+w2)2,求1到每个点的最短路。

题解:

本题的突破口为边权,因为边权大小只有50,所以可以在 d i j k s t r a dijkstra dijkstra上进行一点改动,将原先的一维的 d i s dis dis数组更改为三维,结构体里面多记录一些状态, d i s [ i ] [ j ] [ o d d ] dis[i][j][odd] dis[i][j][odd]表示通过边权为 j j j 的边到达点 i i i 的最短路, o d d odd odd表示点 i i i 是否为两条边的中间那个点。

那么剩下就是跑 d i j k s t r a dijkstra dijkstra即可。

代码:

#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 ");
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_45755679/article/details/113926803
今日推荐