「POI 2003」 Smugglers

题意

给定 \(n\) 种金属的价格,带任意一种金属过境都要交其价格 \(50\%\) 的税。

\(m\) 种关系,每种可以把第 \(a_i\) 种金属单向转换成第 \(b_i\) 种金属,花费 \(c_i\) 的代价。你可以在过境前后进行任意次转换。

最开始你有第 \(1\) 种金属,并需要带第 \(1\) 种金属过境,求最小代价。

分析

比较明显的最短路。

\(i\) 为第 \(i\) 种金属过境前的编号;\(i+n\) 为第 \(i\) 种金属过境后的编号。

\(i\)\(i+n\) 连边,边权为金属价格的一半。

\(a\)\(b\)\(a+n\)\(b+n\) 连边,边权为 \(c\)

从 1 跑最短路,答案为 \(dis_{n+1}\)

用 Dijkstra,时间复杂度为 \(O((n+m)\log (n+m))\)

Code

#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
inline ll read(){ll x=0,f=1;char c=getchar();while(c<48||c>57){if(c==45)f=0;c=getchar();}while(c>47&&c<58)x=(x<<3)+(x<<1)+(c^48),c=getchar();return f?x:-x;}
const ll maxn=5005;
ll n,m,head[maxn<<1],tot,dis[maxn<<1];
bool vis[maxn<<1];
struct edge{ll to,nxt,val;}e[300005];
struct node{
    ll dis,pos;
    inline bool operator<(const node& b)const{
        return b.dis<dis;
    }
};
inline void add(ll u,ll v,ll w){
    e[++tot]=(edge){v,head[u],w};
    head[u]=tot;
}
inline void dij(ll s){
    memset(dis,0x3f,sizeof(dis));
    dis[s]=0;
    priority_queue<node>q;
    q.push((node){0,s});
    while(!q.empty()){
        node u=q.top();q.pop();
        if(vis[u.pos])continue;
        vis[u.pos]=1;
        for(ll i=head[u.pos];i;i=e[i].nxt){
            ll v=e[i].to;
            if(dis[u.pos]+e[i].val<dis[v]){
                dis[v]=dis[u.pos]+e[i].val;
                if(!vis[v])q.push((node){dis[v],v});
            }
        }
    }
}
signed main(){
    n=read();
    for(ll i=1;i<=n;++i)add(i,i+n,read()/2);
    m=read();
    while(m--){
        ll u=read(),v=read(),w=read();
        add(u,v,w),add(u+n,v+n,w);
    }
    dij(1);
    printf("%lld",dis[n+1]);
    return 0;
}
posted @ 2024-03-22 15:26  run-away  阅读(26)  评论(0)    收藏  举报