萌新求教网络流
查看原帖
萌新求教网络流
257621
翼德天尊楼主2020/7/25 11:24
  • 模板题已经过了;

  • 开了弧优化,用了O2以及 registerregister 却依然TLE了六个点

  • 代码如下恳求各位大佬指点(码风自认为还不错)

#include<bits/stdc++.h>
using namespace std;
#define BAXN 4005
#define re register
int n,m,x,head[BAXN],tot=1,ans,cur[BAXN],dep[BAXN];
bool vis[BAXN],viss=1;
struct node{
	int to,next,w;
	node (int a=0,int b=0,int c=0)
		:to(a),next(b),w(c){}
}e[BAXN];
int read(){
	int w=0;
	char c=getchar();
	while (c>'9'||c<'0') c=getchar();
	while (c>='0'&&c<='9'){
		w=(w<<3)+(w<<1)+(c^48);
		c=getchar();
	}
	return w;
}
void adde(int u,int v,int w){
	e[++tot]=node(v,head[u],w);
	head[u]=tot;
}
bool bfs(){
	for (re int i=0;i<=n;i++) dep[i]=1<<30,vis[i]=0,cur[i]=head[i];
	dep[1]=0;
	vis[1]=1;
	queue<int> q;
	q.push(1);
	while (!q.empty()){
		int u=q.front();
		q.pop();
		for (re int i=head[u];i;i=e[i].next){
			int v=e[i].to;
			if (dep[v]>dep[u]+1&&e[i].w){
				dep[v]=dep[u]+1;
				if (!vis[v]){
					vis[v]=1;
					q.push(v);
				}
			}
		}
	}
	if (dep[n]!=1<<30) return 1;
	return 0;
}
int dfs(int u,int flow){
	if (u==n){
		ans+=flow;
		viss=1;
		return flow;
	}
	int used=0;
	for (re int i=cur[u];i;i=e[i].next){
		cur[u]=i;
		int v=e[i].to;
		if (e[i].w&&dep[v]==dep[u]+1){
			int low;
			if (low=dfs(v,min(flow-used,e[i].w))){
				used+=low;
				e[i].w-=low;
				e[i^1].w+=low;
				if (flow==used) break;
			}
		}
	}
	return used;
}
void dinic(){
	while (bfs()){
		while (viss){
			viss=0;
			dfs(1,1<<30);
		} 
	}
}
int main(){
	n=read(),m=read(),x=read();
	for (re int i=1;i<=m;i++){
		int u=read(),v=read(),w=read();
		adde(u,v,w);
		adde(v,u,0);
	}
	dinic();
	if (ans==0) printf("Orz Ni Jinan Saint Cow!\n");
	else if (x%ans==0) printf("%d %d\n",ans,x/ans);
	else printf("%d %d\n",ans,x/ans+1);
    return 0;
}
2020/7/25 11:24
加载中...