传送门
解析:
存边为正向正权,反向负权然后BFS看是否出现矛盾就行了。
不然答案中所求的最小值就是所有联通快中左右差值最大的。
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define re register
#define gc getchar
#define pc putchar
#define cs const
inline int getint(){
re int num;
re char c;
re bool f=0;
while(!isdigit(c=gc()))if(c=='-')f=1;num=c^48;
while(isdigit(c=gc()))num=(num<<1)+(num<<3)+(c^48);
return f?-num:num;
}
cs int N=100005,M=200005;
int last[N],nxt[M<<1],to[M<<1],ecnt;
int w[M<<1];
inline void addedge(int u,int v,int val){
nxt[++ecnt]=last[u],last[u]=ecnt,to[ecnt]=v,w[ecnt]=val;
nxt[++ecnt]=last[v],last[v]=ecnt,to[ecnt]=u,w[ecnt]=-val;
}
int mx,mn;
int dist[N];
bool vis[N];
inline int BFS(int S=1){
mx=mn=0;
queue<int> q;
q.push(S);
dist[S]=0;
vis[S]=true;
while(!q.empty()){
int u=q.front();
q.pop();
for(int re e=last[u],v=to[e];e;v=to[e=nxt[e]]){
if(vis[v]){
if(dist[v]!=dist[u]+w[e])return -1;
continue;
}
vis[v]=true;
dist[v]=dist[u]+w[e];
mx=max(dist[v],mx);
mn=min(dist[v],mn);
q.push(v);
}
}
return mx-mn;
}
int n,m;
signed main(){
n=getint();
m=getint();
for(int re i=1;i<=m;++i){
int u=getint(),v=getint(),val=getint();
addedge(u,v,val);
}memset(dist,0x3f,sizeof dist);
int ans=0;
for(int re i=1;i<=n;++i){
if(vis[i])continue;
int res=BFS(i);
if(res==-1)return puts("impossible"),0;
ans=max(res,ans);
}
cout<<ans;
return 0;
}