码迷,mamicode.com
首页 > 其他好文 > 详细

luogu2774 方格取数问题

时间:2018-01-02 23:29:08      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:i++   +=   turn   论文   min   lin   out   cstring   log   

最大点权独立集,参见胡伯涛论文

#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int m, n, a[105][105], hea[10005], ss, tt, tot, maxFlow, lev[10005], cnt;
const int oo=0x3f3f3f3f;
const int dx[]={0, 1, 0, -1, 0};
const int dy[]={0, 0, 1, 0, -1};
queue<int> d;
struct Edge{
    int too, nxt, val;
}edge[100005];
inline int f(int x, int y){
    return n*(x-1)+y;
}
void add_edge(int fro, int too, int val){
    edge[cnt].nxt = hea[fro];
    edge[cnt].too = too;
    edge[cnt].val = val;
    hea[fro] = cnt++;
}
void addEdge(int fro, int too, int val){
    add_edge(fro, too, val);
    add_edge(too, fro, 0);
}
bool bfs(){
    memset(lev, 0, sizeof(lev));
    lev[ss] = 1;
    d.push(ss);
    while(!d.empty()){
        int x=d.front();
        d.pop();
        for(int i=hea[x]; i!=-1; i=edge[i].nxt){
            int t=edge[i].too;
            if(!lev[t] && edge[i].val>0){
                lev[t] = lev[x] + 1;
                d.push(t);
            }
        }
    }
    return lev[tt]!=0;
}
int dfs(int x, int lim){
    if(x==tt)   return lim;
    int addFlow=0;
    for(int i=hea[x]; i!=-1 && addFlow<lim; i=edge[i].nxt){
        int t=edge[i].too;
        if(lev[t]==lev[x]+1 && edge[i].val>0){
            int tmp=dfs(t, min(lim-addFlow, edge[i].val));
            edge[i].val -= tmp;
            edge[i^1].val += tmp;
            addFlow += tmp;
        }
    }
    return addFlow;
}
void dinic(){
    while(bfs())    maxFlow += dfs(ss, oo);
}
int main(){
    memset(hea, -1, sizeof(hea));
    cin>>m>>n;
    ss = 0; tt = m * n + 1;
    for(int i=1; i<=m; i++)
        for(int j=1; j<=n; j++)
            scanf("%d", &a[i][j]);
    for(int i=1; i<=m; i++)
        for(int j=1; j<=n; j++){
            tot += a[i][j];
            if((i+j)&1) addEdge(ss, f(i,j), a[i][j]);
            else    addEdge(f(i,j), tt, a[i][j]);
            for(int k=1; k<=4; k++){
                int tx=i+dx[k];
                int ty=j+dy[k];
                if(tx<1 || tx>m || ty<1 || ty>n)     continue;
                if((i+j)&1) addEdge(f(i,j), f(tx,ty), oo);
                else    addEdge(f(tx,ty), f(i,j), oo);
            }
        }
    dinic();
    cout<<tot-maxFlow<<endl;
    return 0;
}

luogu2774 方格取数问题

标签:i++   +=   turn   论文   min   lin   out   cstring   log   

原文地址:https://www.cnblogs.com/poorpool/p/8179149.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!