[POJ1001]狼抓兔子 做題筆記

·· / ·– ·· ·-·· ·-·· / ·–· · ·-· ··· ·· ··· - / ··- -· - ·· ·-·· / ·· / ·– ·· -·

題目來源http://www.lydsy.com/JudgeOnline/problem.php?id=1001
這題是最大流,也可以用spfa過,雖然我並不會。。
注意一下這題的邊是無向邊,邊要正反存兩遍,算上網絡流原有的反向邊相當於存了4遍。。空間差幾兆就要MLE了。。。
黃學長那裏有一種比較奇怪的存法,看不太明白。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=1000009,M=6000009,inf=0x3fffffff;
int n,m,s,t,cnt=0,tot=1,maxflow=0;
int pos[1002][1002];
int d[N],q[N],l,r;
int head[N],ver[M<<1],nxt[M<<1],e[M<<1];

void add (int u,int v,int w) {
    ver[++tot]=v;e[tot]=w;nxt[tot]=head[u];head[u]=tot;
    ver[++tot]=u;e[tot]=0;nxt[tot]=head[v];head[v]=tot;
}
bool bfs () {
    l=0;r=0;
    for (int i=0;i<=n*m+5;i++) d[i]=0;
    q[r++]=s; d[s]=1;
    while (l<r) {
        int x=q[l++];
        for (int i=head[x];i;i=nxt[i])
            if (e[i]&&!d[ver[i]]) {
                q[r++]=ver[i];
                d[ver[i]]=d[x]+1;
            }
    }
    if (d[t]) return 1;
    return 0;
}
int dinic (int x,int f) {
    int rest=f;
    if (x==t) return f;
    for (int i=head[x];i&&rest;i=nxt[i]) 
        if (e[i]&&d[ver[i]]==d[x]+1) {
            int now=dinic(ver[i],min(e[i],rest));
            if (!now) d[ver[i]]=0;
            e[i]-=now;
            e[i^1]+=now;
            rest-=now;
        }
    return f-rest;
}
int main () {
    int w,tmp;
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++)
        for (int j=1;j<=m;j++)
            pos[i][j]=++cnt;
    s=1,t=cnt;//直接用(1,1)作源,用(n,m)作匯就行了
    for (int i=1;i<=n;i++)
        for (int j=1;j<=m-1;j++) {
            scanf("%d",&w);
            add(pos[i][j],pos[i][j+1],w);
            add(pos[i][j+1],pos[i][j],w);
        }
    for (int i=1;i<=n-1;i++)
        for (int j=1;j<=m;j++) {
            scanf("%d",&w);
            add(pos[i][j],pos[i+1][j],w);
            add(pos[i+1][j],pos[i][j],w);
        }
    for (int i=1;i<=n-1;i++)
        for (int j=1;j<=m-1;j++) {
            scanf("%d",&w);
            add(pos[i][j],pos[i+1][j+1],w);
            add(pos[i+1][j+1],pos[i][j],w);
        }
    while (bfs()) 
        while (tmp=dinic(s,inf)) maxflow+=tmp;
    printf("%d",maxflow);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章