蒟蒻刚学Dinic,求调
查看原帖
蒟蒻刚学Dinic,求调
785957
miaoborui123456789楼主2025/1/19 16:07

rt

只有八分 QWQ,其他全TLE

#include<bits/stdc++.h>
using namespace std;

#define ll long long
const int N = 2000007;
const ll INF = 0x3f3f3f3f;

ll nxt[N] , to[N] , head[N] , flow[N];
ll top = 0;

ll dep[N];
ll t , s = 1;
ll n , m;
ll maxf;

void add_edge(ll u ,ll v ,ll c){
	nxt[++top] = head[u];
	to[top] = v;
	flow[top] = c;
	head[u] = top;
}

bool bfs(ll s){
	queue<ll> que;
	while(!que.empty()){
		que.pop();
	}
	memset(dep , -1 , sizeof dep);
	dep[s] = 1;
//	bfs_init(s);
	que.push(s);
	while(!que.empty()){
		ll f = que.front();
		que.pop();
		for(int i = head[f] ; ~i ; i = nxt[i]){
			ll v = to[i];
			ll f = flow[i];
			if((f > 0) && (dep[v] == -1)){
				dep[v] = dep[f] + 1;
				que.push(v);
			}
		}
	}
	return dep[t] != -1;
}

ll dfs(ll u , ll dist){
	if(u == t){
		return dist;
	}
	for(int i = head[u] ; ~i ; i = nxt[i]){
		ll v = to[i] , f = flow[i];
		if((dep[v] == dep[u] + 1) && (f != 0)){
			ll df = dfs(v , min(dist , f));
			if(df > 0){
				flow[i] -= df;
				flow[i ^ 1] += df;
				return df;
			}
		}
	}
	return 0;
}

void dinic(){
	maxf = 0;
	ll nowf = 0;
	while(bfs(s)){
		nowf = INF;
		while(nowf){
			nowf = dfs(s , INF);
			maxf += nowf;
		}
	}
}

int main(){
	memset(head , -1 , sizeof head);
	cin>>n>>m;
	s = 1 , t = m;
	for(int i = 1 ; i <= n ; i++){
		ll x , y , f;
		cin>>x>>y>>f;
		add_edge(x,y,f);
		add_edge(y,x,0);
//		tmap[s][e] = c;
	}
	dinic();
	cout<<maxf;
	return 0;
}
2025/1/19 16:07
加载中...