/*************************************************************************
> File Name: UVa11478.cpp
> Author:HaoWei
> Mail:liang199611@outlook.com
> Created Time: 2016年06月18日 星期六 12时08分03秒
************************************************************************/
#include<iostream>
#include<queue>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
const int maxn=555;
const int INF=0x3f3f3f3f;
#define rep(i,n) for(int i=0;i<n;i++)
int M,L,R;
struct Edge{
int from,to,dist;
Edge(){}
Edge(int f,int t,int d):from(f),to(t),dist(d){}
};
struct BellmanFord{
int n,m;
vector<Edge> edges;
vector<int> G[maxn];
bool inq[maxn];
int d[maxn];
int p[maxn];
int cnt[maxn];
void init(int n)
{
this->n=n;
rep(i,n) G[i].clear();
edges.clear();
}
void AddEdge(int from,int to,int dist)
{
edges.push_back(Edge(from,to,dist));
int m=edges.size();
G[from].push_back(m-1);
}
bool negativeCycle(int M)
{
queue<int> Q;
memset(inq,0,sizeof(inq));
memset(cnt,0,sizeof(cnt));
for(int i=0;i<n;i++) {d[i]=0;inq[0]=true;Q.push(i);}
while(!Q.empty())
{
int u=Q.front();Q.pop();
inq[u]=false;
rep(i,G[u].size())
{
Edge e=edges[G[u][i]];
int dist=e.dist-M;
if(d[e.to]>d[u]+dist){
d[e.to]=d[u]+dist;
if(!inq[e.to]) {Q.push(e.to);inq[e.to]=true;if(++cnt[e.to]>=n) return true;}
}
}
}
return false;
}
};
BellmanFord solver;
int main()
{
int V,E;
while(cin>>V>>E)
{
solver.init(V);
rep(i,E){
int u,v,dist;
scanf("%d%d%d",&u,&v,&dist);
u--,v--;
solver.AddEdge(u,v,dist);
}
int L,R,m,ans;
L=1,R=11111;
while(L<=R)
{
m=(R-L)/2+L;
if(solver.negativeCycle(m)) R=m-1;
else L=m+1,ans=m;
}
// cout<<solver.negativeCycle(4)<<endl;
if(L>10000) puts("Infinite");
else if(solver.negativeCycle(1)) puts("No Solution");
else cout<<ans<<endl;
}
return 0;
}
差分约束,
mark一下这种二分的写法