网络流/费用流
费用流入门题……根本就是模板题好吗!
拆点搞定度数限制,也就是每个点最多经过一次……源点汇点除外。
1 /************************************************************** 2 Problem: 1877 3 User: Tunix 4 Language: C++ 5 Result: Accepted 6 Time:900 ms 7 Memory:5972 kb 8 ****************************************************************/ 9 10 //BZOJ 1877 11 #include<vector> 12 #include<cstdio> 13 #include<cstring> 14 #include<cstdlib> 15 #include<iostream> 16 #include<algorithm> 17 #define rep(i,n) for(int i=0;i<n;++i) 18 #define F(i,j,n) for(int i=j;i<=n;++i) 19 #define D(i,j,n) for(int i=j;i>=n;--i) 20 #define pb push_back 21 using namespace std; 22 inline int getint(){ 23 int v=0,sign=1; char ch=getchar(); 24 while(ch<‘0‘||ch>‘9‘){ if (ch==‘-‘) sign=-1; ch=getchar();} 25 while(ch>=‘0‘&&ch<=‘9‘){ v=v*10+ch-‘0‘; ch=getchar();} 26 return v*sign; 27 } 28 const int N=1010,M=200000,INF=~0u>>2; 29 typedef long long LL; 30 /******************tamplate*********************/ 31 int n,m,ans,flow; 32 struct edge{int from,to,v,c;}; 33 struct Net{ 34 edge E[M]; 35 int head[N],next[M],cnt; 36 void ins(int x,int y,int z,int c){ 37 E[++cnt]=(edge){x,y,z,c}; 38 next[cnt]=head[x]; head[x]=cnt; 39 } 40 void add(int x,int y,int z,int c){ 41 ins(x,y,z,c); ins(y,x,0,-c); 42 } 43 int from[N],Q[M],d[N],S,T; 44 bool inq[N]; 45 bool spfa(){ 46 int l=0,r=-1; 47 F(i,1,T) d[i]=INF; 48 d[S]=0; Q[++r]=S; inq[S]=1; 49 while(l<=r){ 50 int x=Q[l++]; 51 inq[x]=0; 52 for(int i=head[x];i;i=next[i]) 53 if(E[i].v>0 && d[x]+E[i].c<d[E[i].to]){ 54 d[E[i].to]=d[x]+E[i].c; 55 from[E[i].to]=i; 56 if (!inq[E[i].to]){ 57 Q[++r]=E[i].to; 58 inq[E[i].to]=1; 59 } 60 } 61 } 62 return d[T]!=INF; 63 } 64 void mcf(){ 65 int x=INF; 66 for(int i=from[T];i;i=from[E[i].from]) 67 x=min(x,E[i].v); 68 for(int i=from[T];i;i=from[E[i].from]){ 69 E[i].v-=x; 70 E[i^1].v+=x; 71 } 72 flow+=x; 73 ans+=x*d[T]; 74 } 75 void init(){ 76 n=getint(); m=getint(); cnt=1; 77 S=1; T=n+n; 78 F(i,1,n) add(i,i+n,1,0); 79 add(1,1+n,INF,0); 80 add(n,n+n,INF,0); 81 int x,y,z; 82 F(i,1,m){ 83 x=getint(); y=getint(); z=getint(); 84 add(x+n,y,1,z); 85 } 86 while(spfa()) mcf(); 87 printf("%d %d\n",flow,ans); 88 } 89 }G1; 90 91 int main(){ 92 #ifndef ONLINE_JUDGE 93 freopen("1877.in","r",stdin); 94 freopen("1877.out","w",stdout); 95 #endif 96 G1.init(); 97 return 0; 98 } 99
时间: 2024-10-27 13:59:11