P1073 最优贸易:https://www.luogu.org/problemnew/show/P1073
题意:
有n个城市,每个城市对A商品有不同的定价,问从1号城市走到n号城市可以最多赚多少差价。(旅游为主,赚钱为辅,所以买入和卖出只进行一次。
思路:
建一个有三层的图,三层都是相同的普通的城市路线,第一层向第二层连从第i个城市买入商品的花费,第二层向第三层连从第i个城市卖出商品的所得。从1 向 第一层的终点 ,向第三层的终点跑一遍最大路就行了。
#include <algorithm>
#include <iterator>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <iomanip>
#include <bitset>
#include <cctype>
#include <cstdio>
#include <string>
#include <vector>
#include <stack>
#include <cmath>
#include <queue>
#include <list>
#include <map>
#include <set>
#include <cassert> using namespace std;
#define lson (l , mid , rt << 1)
#define rson (mid + 1 , r , rt << 1 | 1)
#define debug(x) cerr << #x << " = " << x << "\n";
#define pb push_back
#define pq priority_queue typedef long long ll;
typedef unsigned long long ull;
//typedef __int128 bll;
typedef pair<ll ,ll > pll;
typedef pair<int ,int > pii;
typedef pair<int,pii> p3; //priority_queue<int> q;//这是一个大根堆q
//priority_queue<int,vector<int>,greater<int> >q;//这是一个小根堆q
#define fi first
#define se second
//#define endl '\n' #define OKC ios::sync_with_stdio(false);cin.tie(0)
#define FT(A,B,C) for(int A=B;A <= C;++A) //用来压行
#define REP(i , j , k) for(int i = j ; i < k ; ++i)
#define max3(a,b,c) max(max(a,b), c);
#define min3(a,b,c) min(min(a,b), c);
//priority_queue<int ,vector<int>, greater<int> >que; const ll oo = 1ll<<;
const ll mos = 0x7FFFFFFF; //
const ll nmos = 0x80000000; //-2147483648
const int inf = 0x3f3f3f3f;
const ll inff = 0x3f3f3f3f3f3f3f3f; //
const int mod = ;
const double esp = 1e-;
const double PI=acos(-1.0);
const double PHI=0.61803399; //黄金分割点
const double tPHI=0.38196601; template<typename T>
inline T read(T&x){
x=;int f=;char ch=getchar();
while (ch<''||ch>'') f|=(ch=='-'),ch=getchar();
while (ch>=''&&ch<='') x=x*+ch-'',ch=getchar();
return x=f?-x:x;
}
/*-----------------------showtime----------------------*/ const int maxn = 1e5+; vector<pii>mp[maxn*];
int a[maxn];
int n,m;
void addedge(int s,int t){
mp[s].pb(pii(t, ));
mp[s + n].pb(pii(t + n,));
mp[s + * n].pb(pii(t + * n,)); mp[s].pb(pii(t + n, -a[s]));
mp[s + n].pb(pii(t + * n, a[s]));
} int dis[maxn * ];
bool vis[maxn * ]; int spfa(int s,int t){ memset(dis, -inf,sizeof(dis));
dis[s] = ;
queue<int>que; que.push(s);
vis[s] = true;
while(!que.empty()){
int u = que.front(); que.pop();
vis[u] = false;
for(int i=; i<mp[u].size(); i++){
int v = mp[u][i].fi,w = mp[u][i].se;
if(dis[v] < dis[u] + w){
dis[v] = dis[u] + w;
if(vis[v] == false){
vis[v] = true;
que.push(v);
}
}
}
}
return dis[t];
}
int main(){
scanf("%d%d", &n, &m);
int t = * n + ;
for(int i=; i<=n; i++) scanf("%d", &a[i]);
for(int i=; i<=m; i++){
int u,v,c;
scanf("%d%d%d", &u, &v, &c);
if(c == ) {
addedge(u,v);
}
else {
addedge(u,v);
addedge(v,u);
}
} // addedge(3*n, t);
mp[*n].pb(pii(t,));
mp[n].pb(pii(t, ));
printf("%d\n", spfa(, t));
return ;
}