Cod sursa(job #2067672)

Utilizator Alexa2001Alexa Tudose Alexa2001 Data 16 noiembrie 2017 18:56:35
Problema Pixels Scor 70
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.58 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin ("pixels.in");
ofstream fout ("pixels.out");

const int Nmax = 100 * 100 + 5;
int i, j, k, n, answer, Cost, S, D, C[5];

int code(int x, int y) { return (x-1) * n + y; }

class graph
{
    int c[Nmax][Nmax], t[Nmax];
    vector<int> v[Nmax];

    bool BFS()
    {
        int node;
        memset(t, -1, sizeof(t));

        queue<int> Q;
        Q.push(S); t[S] = 0;

        while(!Q.empty())
        {
            node = Q.front();
            Q.pop();
            for(auto it : v[node])
                if(t[it]==-1 && c[node][it])
                {
                    if(it==D) return 1;
                    t[it] = node;
                    Q.push(it);
                }
        }
        return 0;
    }

    public:
        void add_edge(int x, int y, int capacity)
        {
            c[x][y] = c[y][x] = capacity;
            v[x].push_back(y);
            v[y].push_back(x);
        }

        int max_flow()
        {
            int node, fmin, dad, flow = 0;
            while(BFS())
            {
                for(auto d : v[D])
                if(t[d] != -1)
                {
                    fmin = c[d][D];
                    node = d;
                    while(node != S)
                    {
                        dad = t[node];
                        fmin = min(fmin, c[dad][node]);
                        node = dad;
                    }

                    flow += fmin;
                    c[d][D] -= fmin;
                    c[D][d] += fmin;

                    node = d;
                    while(node != S)
                    {
                        dad = t[node];
                        c[dad][node] -= fmin;
                        c[node][dad] += fmin;
                        node = dad;
                    }
                }
            }
            return flow;
        }
} graph;


int main()
{
    fin >> n;
    S = 0, D = n * n + 1;
    for(i=1; i<=n; ++i)
        for(j=1; j<=n; ++j)
        {
            fin >> Cost;
            graph.add_edge(S, code(i, j), Cost);
            answer += Cost;
        }

    for(i=1; i<=n; ++i)
        for(j=1; j<=n; ++j)
        {
            fin >> Cost;
            graph.add_edge(code(i, j), D, Cost);
            answer += Cost;
        }

    for(i=1; i<=n; ++i)
        for(j=1; j<=n; ++j)
        {
            for(k=0; k<4; ++k) fin >> C[k];
            if(j+1 <= n) graph.add_edge(code(i, j), code(i, j+1), C[1]);
            if(i+1 <= n) graph.add_edge(code(i, j), code(i+1, j), C[2]);
        }

    answer -= graph.max_flow();
    fout << answer << '\n';

    return 0;
}