zoukankan      html  css  js  c++  java
  • POJ 3422 Kaka's Matrix Travels(费用流)

    【题目链接】 http://poj.org/problem?id=3422

    【题目大意】

      给出一个矩阵,从左上角到右下角走K次,每次只能往下或者往右,
      每次走过这个格子就把这里的数字变成0,问k次之后,最多可以获得的总和是多少。

    【题解】

      我们对这个图进行建图,拆点连边,费用为负点权,
      之后得到满流的最小费用的相反数就是答案。

    【代码】

    #include <cstdio>
    #include <algorithm>
    #include <cstring>
    #include <vector>
    using namespace std;
    const int INF=0x3f3f3f3f;
    struct edge{int to,cap,cost,rev;};
    const int MAX_V=10000;
    int V,dist[MAX_V],prevv[MAX_V],preve[MAX_V];
    vector<edge> G[MAX_V];
    void add_edge(int from,int to,int cap,int cost){
        G[from].push_back((edge){to,cap,cost,G[to].size()});
        G[to].push_back((edge){from,0,-cost,G[from].size()-1});
    }
    int min_cost_flow(int s,int t,int f){
        int res=0;
        while(f>0){
            fill(dist,dist+V,INF);
            dist[s]=0;
            bool update=1;
            while(update){
                update=0;
                for(int v=0;v<V;v++){
                    if(dist[v]==INF)continue;
                    for(int i=0;i<G[v].size();i++){
                        edge &e=G[v][i];
                        if(e.cap>0&&dist[e.to]>dist[v]+e.cost){
                            dist[e.to]=dist[v]+e.cost;
                            prevv[e.to]=v;
                            preve[e.to]=i;
                            update=1;
                        }
                    }
                }
            }
            if(dist[t]==INF)return -1;
            int d=f;
            for(int v=t;v!=s;v=prevv[v]){
                d=min(d,G[prevv[v]][preve[v]].cap);
            }f-=d;
            res+=d*dist[t];
            for(int v=t;v!=s;v=prevv[v]){
                edge &e=G[prevv[v]][preve[v]];
                e.cap-=d;
                G[v][e.rev].cap+=d; 
            }
        }return res;
    }
    const int MAX_N=200;
    int N,K,u;
    void solve(){
        int s=0,t=N*N*2-1;
        V=t+1;for(int i=0;i<V;i++)G[i].clear();
        for(int i=0;i<N;i++){
            for(int j=0;j<N;j++){
                scanf("%d",&u);
                int p=i*N+j;
                add_edge(p,N*N+p,1,-u);
                add_edge(p,N*N+p,INF,0);
                if(i+1<N)add_edge(N*N+p,(i+1)*N+j,INF,0);
                if(j+1<N)add_edge(N*N+p,i*N+j+1,INF,0);
            }
        }printf("%d
    ",-min_cost_flow(s,t,K));
    }
    int main(){
        while(~scanf("%d%d",&N,&K)){
            solve();
        }return 0;
    }
  • 相关阅读:
    Vue 02
    Vue 初识
    复杂数据类型之函数 对象
    Collections工具类
    遍历集合的方法总结
    使用Iterator迭代器遍历容器元素(List/Set/Map)
    TreeSet的使用和底层实现
    HashSet基本使用
    HashSet底层实现
    TreeMap的使用和底层实现
  • 原文地址:https://www.cnblogs.com/forever97/p/poj3422.html
Copyright © 2011-2022 走看看