P1073 最优贸易
二分图+spfa
(代码是别人的)
//P1073 最优贸易 #include<bits/stdc++.h> using namespace std; const int mxn=100010; const int inf=1<<18; int n,m; struct node{ int v,len; }; int v[mxn],d[mxn*3+1]; vector<node> g[mxn*3+1]; inline void add(int x,int y){ g[x].push_back((node){y,0}); g[x+n].push_back((node){y+n,0}); g[x+2*n].push_back((node){y+2*n,0}); g[x].push_back((node){y+n,-v[x]}); g[x+n].push_back((node){y+2*n,v[x]}); } queue<int> q; bool inq[mxn*3+1]; void spfa(){ for(int i=1;i<=n;i++){ d[i]=-inf; } d[1]=0; inq[1]=1; q.push(1); while(q.size()){ int tp=q.front(); q.pop(); inq[tp]=0; int sz=g[tp].size(); for(int i=0;i<sz;i++){ node x=g[tp][i]; if(d[x.v]<d[tp]+x.len){ d[x.v]=d[tp]+x.len; if(!inq[x.v]){ q.push(x.v); inq[x.v]=1; } } } } } int main(){ cin>>n>>m; for(int i=1;i<=n;i++){ scanf("%d",&v[i]); } for(int i=1;i<=m;i++){ int x,y,z; scanf("%d%d%d",&x,&y,&z); // g[x].push_back(y); // if(z==2) g[y].push_back(x); add(x,y); if(z==2) add(y,x); } g[n].push_back((node){3*n+1,0}); g[n*3].push_back((node){3*n+1,0}); n=3*n+1; spfa(); cout<<d[n]; return 0; }