AOJ 2266 Cache Strategy(费用流)

【题目链接】 http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=2266

【题目大意】

  有M个桶,N个球,球编号为1到N,每个球都有重量w_i。
  给出一个长K的数列,数列由球的编号构成。开始的时候,桶都是空的。
  接着我们从前往后从数列中取出一个数a_j,执行如下操作:
  如果球a_j已经存在于某一个桶中,那么什么也不干,花费为0,继续。
  如果任何桶中都没有a_j,那么找一个桶放a_j,
  如果该桶里还有球,那么取出原来的球,将a_j放进去。
  这种操作的花费是a_j的重量w_a_j,与桶以及原来的球没关系。
  求最小花费?

【题解】

  我们先假设我们只有一个桶,那么答案就是权值总和,
  然后我们考虑一下如何节省开支,多出来的m-1个桶可以让我们保留一些序号
  一直到下一个相同序号,就节省下了这个序号的费用,
  那这样,我们就得到了这个桶在这个时间区段,被这个序号所占用的信息
  我们将每个桶需要保留到下一个相同需要需要的时间区段整理成一个线段集合,
  那我们只要求出这些线段在最多相交m-1次的情况下能够得到的最大权值和,
  就是我们可以节省的最大开支了。

【代码】

#include <cstdio>
#include <algorithm>
#include <cstring>
#include <vector>
#include <utility>
using namespace std;
const int INF=0x3f3f3f3f;
typedef long long LL;
struct edge{
    int to,cap,cost,rev;
    edge(int to,int cap,int cost,int rev):to(to),cap(cap),cost(cost),rev(rev){}
};
const int MAX_V=10010;
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;
}
void clear(){for(int i=0;i<=V;i++)G[i].clear();}
const int MAX_N=10010;
int M,N,K,w[MAX_N],lst[MAX_N],a[MAX_N];
int solve(){
    for(int i=1;i<=N;i++)scanf("%d",&w[i]);
    for(int i=1;i<=K;i++)scanf("%d",&a[i]);
    int cnt=unique(a+1,a+K+1)-(a+1);
    int res=0;
    memset(lst,0,sizeof(lst));
    V=cnt+1; clear();
    for(int i=1;i<=cnt;i++){
        res+=w[a[i]];
        if(lst[a[i]])add_edge(lst[a[i]],i-1,1,-w[a[i]]);
        lst[a[i]]=i;
    }for(int i=1;i<cnt;i++)add_edge(i,i+1,INF,0);
    printf("%d
",res+min_cost_flow(1,cnt,M-1));
}
int main(){
    while(~scanf("%d%d%d",&M,&N,&K))solve();
    return 0;
}
原文地址:https://www.cnblogs.com/forever97/p/aoj2266.html