[bzoj1001] 狼抓兔子

  • 題意(原題):
  • 給出一個網格(有斜向邊),左上角爲源點,右下角爲匯點,每條邊有流量,請問截留所有流量的代價爲多少(截留一條邊的代價與該邊實際使用最大流量相等(應該沒理解錯))。
  • 思路:
  • 最大流:每條邊每單位時間允許經過一定流量,源點流量無限,則爲每單位時間匯點所能接受的最大流量。
  • 最小割定理:把一個圖源點匯點分開,代價等於該圖最大流。
  • 因此我們使用網絡流解決這一問題。我使用的是dinic模版(貌似有些過時?)
  • 代碼:
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#define MAXN 1000001
using namespace std;
struct node
{
    int x,y,c,next,other;
}a[MAXN*6];int len=0,n,m,st,ed,last[MAXN],list[MAXN],h[MAXN];
int getp(int x,int y)
{
    return (x-1)*m+y;
}
void ins(int x,int y,int c)
{
    len++;
    a[len].x=x;a[len].y=y;a[len].c=c;
    a[len].next=last[x];last[x]=len;a[len].other=len+1; 
    len++;
    a[len].x=y;a[len].y=x;a[len].c=c;
    a[len].next=last[y];last[y]=len;a[len].other=len-1;
}
bool bfs()
{
    int head=1,tail=1;list[1]=st;
    memset(h,0,sizeof(h));h[st]=1;
    while(head<=tail)
    {
        int x=list[head];
        for(int k=last[x];k;k=a[k].next)
        {
            int y=a[k].y;
            if(!h[y]&&a[k].c)
            {
                h[y]=h[x]+1;
                list[++tail]=y;
            }
        }
        head++;
    }
    return h[ed]?true:false;
}
int dfs(int x,int flow)
{
    if(x==ed)return flow;
    int cnt=0;
    for(int k=last[x];k;k=a[k].next)
    {
        int y=a[k].y;
        if(a[k].c&&h[x]+1==h[y]&&flow>cnt)
        {
            int z=dfs(y,min(a[k].c,flow-cnt));
            cnt+=z;a[k].c-=z;a[a[k].other].c+=z;
        }
    }
    if(!cnt)h[x]=0;
    return cnt;
}
int main()
{
    scanf("%d%d",&n,&m);st=getp(1,1);ed=getp(n,m);
    int x;
    for(int i=1;i<=n;i++)
        for(int j=1;j<m;j++)
        {
            scanf("%d",&x);
            ins(getp(i,j),getp(i,j+1),x);
        }
    for(int i=1;i<n;i++)
        for(int j=1;j<=m;j++)
        {
            scanf("%d",&x);
            ins(getp(i,j),getp(i+1,j),x);
        }
    for(int i=1;i<n;i++)
        for(int j=1;j<m;j++)
        {
            scanf("%d",&x);
            ins(getp(i,j),getp(i+1,j+1),x);
        }
    int ans=0;
    while(bfs())
    {
        int x=1;
        while(x)
        {
            x=dfs(st,999999999);
            ans+=x;
        }
    }
    printf("%d\n",ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章