Cod sursa(job #2067714)

Utilizator Alexa2001Alexa Tudose Alexa2001 Data 16 noiembrie 2017 19:38:05
Problema Pixels Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.74 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 t[Nmax], come[Nmax], c[10 * Nmax], cnt = 0;
    vector< pair<int,int> > v[Nmax];

    bool BFS()
    {
        int node, i, vecin;
        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.first] == -1 && c[it.second])
                {
                    if(it.first == D) return 1;
                    t[it.first] = node;
                    come[it.first] = it.second;
                    Q.push(it.first);
                }
        }
        return 0;
    }

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

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

                    flow += fmin;
                    c[it.second^1] -= fmin;
                    c[it.second] += fmin;

                    node = d;
                    while(node != S)
                    {
                        c[come[node]] -= fmin;
                        c[come[node] ^ 1] += fmin;
                        node = t[node];
                    }
                }
            }
            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;
}