代码:
#include<queue> #include<stdio.h> #include<string.h> #include<algorithm> #define N 1100 #define M 4100 using namespace std; int X[M],Y[M],A[M],B[M]; int n,m,in[N],out[N]; int f[N],size[N]; int next[M<<1],to[M<<1],flow[M<<1],head[N],ce; int S,T,dis[N]; queue<int>q; void init() { memset(in,0,sizeof(in)); memset(out,0,sizeof(out)); memset(head,0,sizeof(head)); ce=1; for(int i=1;i<=n;i++) f[i]=i,size[i]=1; } void add(int x,int y,int fl) { to[++ce]=y; flow[ce]=fl; next[ce]=head[x]; head[x]=ce; to[++ce]=x; flow[ce]=0; next[ce]=head[y]; head[y]=ce; } int find(int x) { return f[x]==x?x:f[x]=find(f[x]); } void Link(int x,int y) { x=find(x),y=find(y); if(x!=y) { if(size[x]>size[y]) swap(x,y); f[x]=y,size[y]+=size[x]; } } bool BFS() { memset(dis,0,sizeof(dis)); dis[S]=1; q.push(S); int x,y,i; while(!q.empty()) { x=q.front(),q.pop(); for(i=head[x];i;i=next[i]) { if(flow[i]) { if(!dis[y=to[i]]) dis[y]=dis[x]+1,q.push(y); } } } return !!dis[T]; } int dfs(int x,int ma) { if(x==T) return ma; int i,y,ret,temp; for(i=head[x],ret=0;i;i=next[i]) { if(flow[i]&&dis[y=to[i]]==dis[x]+1) { temp=dfs(y,min(ma,flow[i])); flow[i]-=temp; flow[i^1]+=temp; ret+=temp; if(ret==ma) return ret; } } return ret; } bool judge(int lim) { int i,x,y,ans,top; init(); for(i=1;i<=m;i++) { if(A[i]<=lim&&B[i]<=lim) { out[X[i]]++; in[Y[i]]++; Link(X[i],Y[i]); add(Y[i],X[i],1); } else if(A[i]<=lim) { out[X[i]]++; in[Y[i]]++; Link(X[i],Y[i]); } else if(B[i]<=lim) { out[Y[i]]++; in[X[i]]++; Link(X[i],Y[i]); } else return 0; } if(size[find(1)]!=n) return 0; top=ce; for(i=1;i<=n;i++) { if(abs(in[i]-out[i])&1) return 0; if(in[i]>out[i]) { add(S,i,in[i]-out[i]>>1); } else if(in[i]<out[i]) { add(i,T,out[i]-in[i]>>1); } } ans=0; while(BFS()) { ans+=dfs(S,0x3f3f3f3f); } for(i=top+1;i<=ce;i+=2) { if(flow[i]) return 0; } return 1; } int main() { int i,j,k,l,r,mid; scanf("%d%d",&n,&m); for(i=1;i<=m;i++) scanf("%d%d%d%d",X+i,Y+i,A+i,B+i); l=1,r=1000; S=n+1,T=n+2; while(l<=r) { mid=l+r>>1; if(judge(mid)) r=mid-1; else l=mid+1; } if(l>1000) puts("NIE"); else printf("%d\n",l); return 0; }