最优贸易(bfs+分层图)

最优贸易

题目链接:最优贸易
考点:bfs+分层思想
题意:可以在i号点买入水晶球,然后在后面的路径上卖出水晶球,只能进行一次,求最多能赚多少钱
思路:很容易想到分层图
第一层为啥也不干,不买入,不卖出
第二次为买入
第三层为卖出
具体看代码注释
代码部分:

#include"bits/stdc++.h"
using namespace std;
#define rep(i,a,n) for(int i=a;i<=n;i++)
#define rpe(i,a,n) for(int i=a;i>=n;i--)
#define js ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
typedef long long ll;
inline ll read() { ll s = 0, w = 1; char ch = getchar(); for (; !isdigit(ch); ch = getchar()) if (ch == '-') w = -1; for (; isdigit(ch); ch = getchar())    s = (s << 1) + (s << 3) + (ch ^ 48); return s * w; }
inline void write(ll x) { if (!x) { putchar('0'); return; } char F[40]; ll tmp = x > 0 ? x : -x; if (x < 0)putchar('-');    int cnt = 0;    while (tmp > 0) { F[cnt++] = tmp % 10 + '0';        tmp /= 10; }    while (cnt > 0)putchar(F[--cnt]); }
inline ll gcd(ll x, ll y) { return y ? gcd(y, x % y) : x; }
ll qpow(ll a, ll b) { ll ans = 1;    while (b) { if (b & 1)    ans *= a;        b >>= 1;        a *= a; }    return ans; }    ll qpow(ll a, ll b, ll mod) { ll ans = 1; while (b) { if (b & 1)(ans *= a) %= mod; b >>= 1; (a *= a) %= mod; }return ans % mod; }
typedef pair<int,int> pii;

const int N=1e5+9,M=3*5e5+9;
vector<pii> e[M];
int n,m;
int a[N];
int d[N*3];
bool vis[N*3];
const int inf=0x3f;
void slove(){
    cin>>n>>m;
    rep(i,1,n)cin>>a[i];
    int u,v,opx;
    rep(i,1,m){
        cin>>u>>v>>opx;
        e[u].push_back({v,0});//第一层之间
        e[u].push_back({v+n,-a[u]});//第一层到第二次就等于买入
        e[u+n].push_back({v+n,0});//第二层之间
        e[u+n].push_back({v+2*n,a[u]});//第二层到第三层就等于卖出
        e[u+2*n].push_back({v+2*n,0});//第三层之间
        if(opx==2){//双向通路
            int y=u;u=v;v=y;
            e[u].push_back({v,0});
        e[u].push_back({v+n,-a[u]});
        e[u+n].push_back({v+n,0});
        e[u+n].push_back({v+2*n,a[u]});
        e[u+2*n].push_back({v+2*n,0});
        }
    }
    memset(d,-0x3f,sizeof d);
    d[1]=0;
    vis[1]=true;
    queue<int> q;
    q.push(1);
    while(q.size()){//bfs暴力遍历
        int k=q.front();
        q.pop();
        vis[k]=false;
        for(auto ed:e[k]){
            int v=ed.first;
            int val=ed.second;
            if(d[k]+val>d[v]){
                d[v]=d[k]+val;
                if(!vis[v]){
                    q.push(v);
                    vis[v]=true;
                }
            }
        }
    }
    cout<<max(d[n],d[3*n]);
}

int main(){
    js;
    int t=1;
    //cin>>t;
    while(t--)slove();
}

posted @ 2023-11-07 22:41  锦林不睡觉  阅读(16)  评论(0)    收藏  举报