您的位置:首页 > 理论基础 > 计算机网络

HDU4280 Island Transport【网络流】

2017-09-13 17:43 281 查看
题意:从最左边的点 运人到 最右边的点 最多能运多少人

思路:裸的的最大流,就是卡时间,用邻接表的Dinic

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<stdlib.h>
#include<math.h>
#include<vector>
#include<list>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
#include<numeric>
#include<functional>
using namespace std;
typedef long long ll;
const int maxn = 100005;

struct Edge
{
int to,next,cap;
}edge[maxn*3];
int head[maxn],tot,d[maxn];

void init()
{
memset(head,-1,sizeof head);
tot = 0;
}

void add(int x,int y,int cap)
{
edge[tot].to = y;
edge[tot].cap = cap;
edge[tot].next = head[x];
head[x] = tot++;

edge[tot].to = x;
edge[tot].cap = cap;
edge[tot].next = head[y];
head[y] = tot++;
}

bool bfs(int s,int t)
{
queue<int> p;
memset(d,0,sizeof(d));
p.push(s);
d[s]=1;
while(!p.empty())
{
int top=p.front();
p.pop();
if(top==t)
return true;
for(int i=head[top]; i!=-1; i=edge[i].next)
{
if(!d[edge[i].to] && edge[i].cap>0)
{
d[edge[i].to]=d[top]+1;
p.push(edge[i].to);
}
}
}
return false;
}

int dfs(int now,int t,int maxf)
{
int f,res=0;
if(now==t)
return maxf;
for(int i=head[now]; i!=-1; i=edge[i].next)
{
if((d[edge[i].to]==d[now]+1)&&edge[i].cap>0)
{

f=dfs(edge[i].to,t,min(maxf-res,edge[i].cap));
edge[i].cap-=f;
edge[i^1].cap+=f;
res+=f;
if(res==maxf)
return res;
}
}
if(res==0)
d[now]=0;
return res;
}

int maxflow(int s,int t)
{
int res=0;
while(bfs(s,t))
res+=dfs(s,t,0x3f3f3f3f);
return res;
}

int main(void)
{
int T,n,m;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
init();
int l = 0x3f3f3f3f,r = -0x3f3f3f3f;
int s,t;
for(int i = 1; i <= n; i++)
{
int a,b;
scanf("%d%d",&a,&b);
if(a < l)
{
l = a;
s = i;
}
if(a > r)
{
r = a;
t = i;
}
}
for(int i = 0; i < m; i++)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
}
int ans = maxflow(s,t);
printf("%d\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: