http://www.elijahqi.win/archives/2786
题意:n个点m条边的有向图求1~n最小割 但是要求1~n之间的路径不能不经过割边(显然) 且1~n的路径中不能有任何一条经过两条以上的割边
那么考虑一个割割开之后分成s,t集合那么如果会产生这种问题一定是集合t有连回s的边 那么会重复转圈走所以给每条边都添加inf的边 让这样的问题消失 然后跑最大流即可 不存在的话输出-1即可
#include
#include
#include
#include
#include
#define ll long long
#define N 1100
#define inf 1e14
using namespace std;
inline char gc(){
static char now[1<<16],*S,*T;
if (T==S){T=(S=now)+fread(now,1,1<<16,stdin);if (T==S) return EOF;}
return *S++;
}
inline int read(){
int x=0,f=1;char ch=gc();
while(ch<'0'||ch>'9') {if (ch=='-') f=-1;ch=gc();}
while(ch<='9'&&ch>='0') x=x*10+ch-'0',ch=gc();
return x*f;
}
int h[N],num=1,n,m,x[N<<1],y[N<<1],z[N<<1],level[N],T,cur[N];bool visit1[N],visit2[N];
struct node{
int y,next;ll z;
}data[N<<3];
inline void insert1(int x,int y,ll z){
data[++num].y=y;data[num].next=h[x];data[num].z=z;h[x]=num;
// data[++num].y=x;data[num].next=h[y];data[num].z=0;h[y]=num;
}
vector<int> eg1[N],eg2[N];
inline void dfs1(int x){
visit1[x]=1;
for (int i=0;iint y=eg1[x][i];if (visit1[y]) continue;dfs1(y);
}
}
inline void dfs2(int x){
visit2[x]=1;
for (int i=0;iint y=eg2[x][i];if (visit2[y]) continue;dfs2(y);
}
}
inline bool bfs(){
queue<int>q;q.push(1);memset(level,0,sizeof(level));level[1]=1;
while(!q.empty()){
int x=q.front();q.pop();
for (int i=h[x];i;i=data[i].next){
int y=data[i].y;if(level[y]||!data[i].z) continue;
level[y]=level[x]+1;if (y==T) return 1;q.push(y);
}
}return 0;
}
inline ll dfs(int x,ll s){
if (x==T) return s;ll ss=s;
for (int &i=cur[x];i;i=data[i].next){
int y=data[i].y;ll z=data[i].z;
if (level[x]+1==level[y]&&z){
ll xx=dfs(y,min(z,s));if (!xx) level[y]=0;
s-=xx;data[i].z-=xx;data[i^1].z+=xx;if (!s) return ss;
}
}return ss-s;
}
int main(){
freopen("t2.in","r",stdin);
int TT=read();
while(TT--){
n=read();m=read();memset(visit1,0,sizeof(visit1));memset(visit2,0,sizeof(visit2));
for (int i=1;i<=n;++i) eg1[i].clear(),eg2[i].clear();
for (int i=1;i<=m;++i){
x[i]=read();y[i]=read();z[i]=read();
eg1[x[i]].push_back(y[i]);eg2[y[i]].push_back(x[i]);
}dfs1(1);dfs2(n);ll ans=0;T=n;num=1;memset(h,0,sizeof(h));
for (int i=1;i<=m;++i){
insert1(x[i],y[i],z[i]);
if (visit1[x[i]]&&visit2[y[i]]) insert1(y[i],x[i],inf);else insert1(y[i],x[i],0);
}
while(bfs()) memcpy(cur,h,sizeof(h)),ans+=dfs(1,inf);
printf("%lld\n",ans>=inf?-1:ans);
}
return 0;
}