Cod sursa(job #751503)

Utilizator PetcuIoanPetcu Ioan Vlad PetcuIoan Data 26 mai 2012 11:26:24
Problema Cc Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.81 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

const int N=351,inf=1<<30;
int cap[N][N],cost[N][N],flux[N][N],dist[N],T[N],n;
class compare
{
    public:
    bool operator()(const int &a,const int &b)
    {
        return dist[a]<dist[b];
    }
};
queue <int> Q;
vector<int> a[N];

ifstream in("cc.in");
ofstream out("cc.out");

inline int dif(int x,int y)
{
    return cap[x][y]-flux[x][y];
}

bool bf(int x,int D)
{
    for (int i=1;i<=n;i++)
        dist[i]=inf;
    while (!Q.empty())
        Q.pop();
    dist[x]=0;
    Q.push(x);
    while (!Q.empty())
    {
        x=Q.front();Q.pop();
        if (x==D)
            continue;
        for (vector<int>::iterator i=a[x].begin();i!=a[x].end();i++)
            if (dif(x,*i)>0 && dist[x]+cost[x][*i]<dist[*i])
            {
                dist[*i]=dist[x]+cost[x][*i];
                T[*i]=x;
                Q.push(*i);
            }
    }
    return dist[D]!=inf;
}

int flow(int S,int D)
{
    int C=0,M;
    while (bf(S,D))
    {
        M=inf;
        for (int i=D;i!=S;i=T[i])
            M=min(M,dif(T[i],i));
        if (!M)
            break;
        for (int i=D;i!=S;i=T[i])
        {
            flux[T[i]][i]+=M;
            flux[i][T[i]]-=M;
        }
        C+=M*dist[D];
    }
    return C;
}

int main()
{
    int S,D;
    in>>n;
    S = 0;
    D = n * 2 + 1;

    for(int i = 1; i <= n; ++i){
      for(int j = 1; j <= n; ++j){
        int aux;
        in >> aux;
        a[i].push_back(j + n);
        a[j + n].push_back(i);
        cap[i][j + n] = 1;
        cost[i][j + n] = aux;
        cost[j + n][i] = -aux;
      }
      a[i].push_back(S);
      a[S].push_back(i);
      cap[S][i] = 1;

      a[i + n].push_back(D);
      a[D].push_back(i + n);
      cap[i + n][D] = 1;
    }

    n = n + n + 1;

    out<<flow(S,D)<<"\n";
    return 0;
}