Cod sursa(job #3193918)

Utilizator sirbu27Sirbu Iulia-Georgiana sirbu27 Data 16 ianuarie 2024 02:40:49
Problema Taramul Nicaieri Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.39 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <cstring>
#include <climits>

using namespace std;

const int MAXN = 202; // N * 2 + 2
int capacity[MAXN][MAXN];
int flow[MAXN][MAXN];
int parent[MAXN];
bool visited[MAXN];
int N;

bool bfs(int s, int t)
{
    memset(visited, 0, sizeof(visited));
    queue<int> q;
    q.push(s);
    visited[s] = true;
    parent[s] = -1;

    while (!q.empty())
    {
        int u = q.front();
        q.pop();

        for (int v = 0; v < 2 * N + 2; ++v)
        {
            if (!visited[v] && capacity[u][v] - flow[u][v] > 0)
            {
                q.push(v);
                parent[v] = u;
                visited[v] = true;
            }
        }
    }

    return visited[t];
}

int fordFulkerson(int s, int t)
{
    int max_flow = 0;

    while (bfs(s, t))
    {
        int path_flow = INT_MAX;
        for (int v = t; v != s; v = parent[v])
        {
            int u = parent[v];
            path_flow = min(path_flow, capacity[u][v] - flow[u][v]);
        }

        for (int v = t; v != s; v = parent[v])
        {
            int u = parent[v];
            flow[u][v] += path_flow;
            flow[v][u] -= path_flow;
        }

        max_flow += path_flow;
    }

    return max_flow;
}

int main()
{
    ifstream fin("harta.in");
    ofstream fout("harta.out");

    fin >> N;
    int total_in_deg = 0, total_out_deg = 0;
    vector<pair<int, int>> cities(N);

    for (int i = 0; i < N; ++i)
    {
        fin >> cities[i].first >> cities[i].second;
        total_out_deg += cities[i].first;
        total_in_deg += cities[i].second;
    }

    int source = 2 * N, sink = 2 * N + 1;

    for (int i = 0; i < N; ++i)
    {
        capacity[source][i] = cities[i].first;
        capacity[i + N][sink] = cities[i].second;

        for (int j = 0; j < N; ++j)
        {
            if (i != j)
            {
                capacity[i][j + N] = 1;
            }
        }
    }

    int max_flow = fordFulkerson(source, sink);

    fout << max_flow << endl;
    for (int i = 0; i < N; ++i)
    {
        for (int j = 0; j < N; ++j)
        {
            if (flow[i][j + N] > 0)
            {
                fout << i + 1 << " " << j + 1 << endl;
            }
        }
    }

    fin.close();
    fout.close();

    return 0;
}