RT,算法是 dinic
。恳请各位帮忙查查哪里拖了效率。
TLE #1 #2 #3
#include <bits/stdc++.h>
const int N=1e4+5,M=2e5+5,INF=1e9;
using namespace std;
int a[N],d[N],now[N];
int head[N],nt[M],to[M],val[M];
int n,m,s,t,num,tot;
bool BFS(){
memset(d,0,sizeof d);
queue<int>q;q.push(s);now[s]=head[s];d[s]=1;
while(!q.empty()){
int x=q.front();q.pop();
for(int i=head[x];i;i=nt[i]){
int y=to[i];
if(d[y]||!val[i]) continue;
q.push(y);d[y]=d[x]+1;
now[y]=head[y];
if(y==t) return true;
}
}
return false;
}
int dinic(int p,int flow){
if(p==t) return flow;
int i,res=flow;
for(i=now[p];i&&res;i=nt[i]){
int y=to[i];
if(d[y]!=d[p]+1||!val[i]) continue;
int k=dinic(y,min(val[i],res));
if(!k) d[y]=0;
val[i]-=k;val[i^1]+=k;
res-=k;
}
now[p]=i;
return flow-res;
}
inline void Add(int x,int y,int z){
++num;nt[num]=head[x];head[x]=num;to[num]=y;val[num]=z;
++num;nt[num]=head[y];head[y]=num;to[num]=x;val[num]=0;
}
void Init(){
num=1;tot=0;
memset(a,0,sizeof a);
memset(head,0,sizeof head);
}
void D(){
int S,T,sum=0,ans=0;
S=0;T=n+m+1;s=n+m+2;t=n+m+3;
Init();
for(int i=1;i<=m;++i){
int x;
scanf("%d",&x),Add(i+n,T,INF),a[T]+=x,a[i+n]-=x;
}
for(int i=1;i<=n;++i){
int x,y,l,r;
scanf("%d%d",&x,&y);Add(S,i,y);
for(int j=1;j<=x;++j){
scanf("%d%d%d",&y,&l,&r);
Add(i,y+n+1,r-l);
a[y+n+1]+=l;a[i]-=l;
}
}
Add(T,S,INF);
for(int i=S;i<=T;++i)
if(a[i]<0) Add(i,t,-a[i]);
else Add(s,i,a[i]),sum+=a[i];
int flow=0;
while(BFS())
while(flow=dinic(s,INF)) ans+=flow;
if(ans!=sum) return (void)puts("-1\n");
ans=0;s=S,t=T;
while(BFS())
while(flow=dinic(s,INF)) ans+=flow;
printf("%d\n\n",ans);
}
int main(){
while(~scanf("%d%d",&n,&m))
D();
return 0;
}