列表

详情


NC201104. Flow

描述

One of 's research interests is the maximum flow problem.
A directed graph with vertices is if the following condition is satisfied:
A set of paths is vertex-independent if they do not have any internal vertex in common.
A vertex in a path is called internal if it is not an endpoint of that path.
A path is simple if its vertices are distinct.
Let be a graph with vertices and edges. Each edge has a non-negative integral capacity. You are allowed to perform the following operation any (including ) times to make the maximum flow from vertex to vertex as large as possible:
Let be an edge with positive capacity. Reduce the capacity of by and increase the capacity of another edge by .
wants to know what is the minimum number of operations to achieve it?

输入描述

The first line contains two integers  and  ().
Each of the next lines contains three integers and , denoting an edge from to with capacity (, ).
It's guaranteed that the input is a universe graph without multiple edges and self-loops.

输出描述

Output a single integer --- the minimum number of operations.

示例1

输入:

4 3
1 2 1
2 3 2
3 4 3

输出:

1

示例2

输入:

4 4
1 2 1
1 3 1
2 4 2
3 4 2

输出:

1

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

C++14(g++5.4) 解法, 执行用时: 124ms, 内存消耗: 15384K, 提交时间: 2020-01-12 19:47:13

#pragma GCC optimize("-Ofast","-funroll-all-loops")
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e5+10,M=N<<1;
int n,m,flow,res,cnt;
int head[N],nex[M],to[M],w[M],tot;
vector<int> v[N];
inline void add(int a,int b,int c){
	to[++tot]=b; nex[tot]=head[a]; w[tot]=c; head[a]=tot;
}
void dfs(int x){
	if(x==n)	return ;
	for(int i=head[x];i;i=nex[i]){
		v[cnt].push_back(w[i]);	dfs(to[i]);
	}
}
signed main(){
	ios::sync_with_stdio(false);	cin.tie(nullptr);
	cin>>n>>m;
	for(int i=1,a,b,c;i<=m;i++)	cin>>a>>b>>c,add(a,b,c),flow+=c;
	for(int i=head[1];i;i=nex[i]){
		v[++cnt].push_back(w[i]); dfs(to[i]);
		sort(v[cnt].begin(),v[cnt].end());
	}
	flow/=v[1].size();
	for(int i=0,s;i<v[1].size();i++){
		s=0;
		for(int j=1;j<=cnt;j++)	s+=v[j][i];
		if(s>=flow)	break;
		res+=flow-s;
	}
	cout<<res;
	return 0;
}

C++11(clang++ 3.9) 解法, 执行用时: 234ms, 内存消耗: 14976K, 提交时间: 2020-02-19 16:54:04

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

typedef long long ll;

const int maxn=1e5+10;

int n,m,k;

vector< pair<ll,ll> >g[maxn];
vector<int> a[maxn];

void dfs( int x )
{
	if( x==n ) 
	{
		sort(a[k].begin(),a[k].end());
		return;
	}
	for( auto v:g[x] )
	{
		if( x==1 ) k++;
		a[k].push_back( v.second );
		dfs( v.first );
	}
}

int main()
{
	scanf("%d%d",&n,&m);
	ll avg=0;
	for( int i=0;i<m;i++ )
	{
		int u,v,w;
		scanf("%d%d%d",&u,&v,&w);
		g[u].push_back( make_pair(v,w) );
		avg+=w;
	}
	k=0;
	dfs(1);
	
	ll ans=0;
	avg/=a[1].size(); // 最大流量 
	for( int i=0;i<a[1].size();i++ )
	{
		ll tmp=0;
		for( int j=1;j<=k;j++ ) tmp+=a[j][i];
		if( tmp>=avg ) break;   
		ans+=avg-tmp;  // 操作次数 
	}
	printf("%lld\n",ans);
}

上一题