设sum(u)为在结点u上的全部操作叠加(操作顺序无影响)
则原边w(a,b)变为w(a,b)+sum(a)-sum(b)
二分答案x,则w(a,b)+sum(a)-sum(b)>=x,即sum(b)-sum(a)<=w(a,b)-x
差分约束系统
构图用SPFA判断是否有解。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
//#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cstdlib> #include<algorithm> #include<iostream> #include<sstream> #include<cmath> #include<climits> #include<string> #include<map> #include<queue> #include<vector> #include<stack> #include<set> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair<int,int> pii; #define pb(a) push(a) #define INF 0x1f1f1f1f #define lson idx<<1,l,mid #define rson idx<<1|1,mid+1,r #define PI 3.1415926535898 template<class T> T min(const T& a,const T& b,const T& c) { return min(min(a,b),min(a,c)); } template<class T> T max(const T& a,const T& b,const T& c) { return max(max(a,b),max(a,c)); } void debug() { #ifdef ONLINE_JUDGE #else freopen("d:\\in1.txt","r",stdin); freopen("d:\\out1.txt","w",stdout); #endif } int getch() { int ch; while((ch=getchar())!=EOF) { if(ch!=' '&&ch!='\n')return ch; } return EOF; } struct Edge { int from,to; int dist; }; const int maxn=505; vector<int> g[maxn]; vector<Edge> edge; int d[maxn]; int inq[maxn]; int inq_cnt[maxn]; int n,m; int limit; void init() { limit=(int)sqrt(n)+1; for(int i=0;i<=n;i++)g[i].clear(); edge.clear(); } void add(int u,int v,int w) { Edge e=(Edge){u,v,w}; edge.push_back(e); g[u].push_back(edge.size()-1); } bool negativeCycle(int s) { queue<int> q; memset(inq,0,sizeof(inq)); memset(inq_cnt,0,sizeof(inq_cnt)); for(int i=0;i<=n;i++) { d[i]=0; inq[i]=1; q.push(i); } while(!q.empty()) { int u=q.front();q.pop(); inq[u]=0; for(int i=0;i<g[u].size();i++) { Edge &e=edge[g[u][i]]; if(d[u]+e.dist<d[e.to]) { d[e.to]=d[u]+e.dist; if(!inq[e.to]) { inq[e.to]=1; q.push(e.to); if(++inq_cnt[e.to]>limit)return true; } } } } return false; } bool check(int x) { for(int i=0;i<m;i++) edge[i].dist-=x; int flag=negativeCycle(0); for(int i=0;i<m;i++) edge[i].dist+=x; return flag; } int main() { while(scanf("%d%d",&n,&m)!=EOF) { init(); for(int i=1;i<=m;i++) { int u,v; int w; scanf("%d%d%d",&u,&v,&w); add(u,v,w); } for(int i=1;i<=n;i++) add(0,i,0); if(!check(10005))printf("Infinite\n"); else if(check(1))printf("No Solution\n"); else { int l=1,r=10005; while(l<r) { int mid=l+(r-l)/2; if(!check(mid)) l=mid+1; else r=mid; } printf("%d\n",l-1); } } return 0; }