Cod sursa(job #3137017)

Utilizator BetJohn000Ioan Benescu BetJohn000 Data 10 iunie 2023 11:06:30
Problema Flux maxim Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.39 kb
// folosesc implementarea anterioara doar ca la final fac un dfs din sursa
// si vad ce noduri nu am vizitat. nodurile se impart apoi in doua grupe: cele vizitate si cele nevizitate, si asta e raspunsul

#include <bits/stdc++.h>

using namespace std;

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

vector<vector<int>> residualGraph;
vector<vector<int>> adjList;
vector<int> tt;
vector<int> viz;
int n, m;

bool bfs()
{
    for(int i = 1; i <= n; ++i)
    {
        tt[i] = 0;
        viz[i] = 0;
    }
    viz[1] = 1;
    queue<int> q;
    q.push(1);
    while(!q.empty())
    {
        int crt = q.front();
        q.pop();
        for(int node : adjList[crt])
        {
            if(viz[node] == 0 && residualGraph[crt][node] > 0)
            {
                q.push(node);
                viz[node] = 1;
                tt[node] = crt;
                if(node == n)
                    return true;
            }
        }
    }
    return false;
}

void dfs(int node){
    viz[node] = 1;
    for(int ng : adjList[node]){
        if(viz[ng] == 0 && residualGraph[node][ng] != 0){
            dfs(ng);
        }
    }
}

int getFlow()
{
    int flow = INT_MAX;
    int i = n;
    while(i != 1)
    {
        flow = min(flow, residualGraph[tt[i]][i]);
        i = tt[i];
    }
    return flow;
}

void updateResidual(int flow)
{
    int i = n;
    while(i != 1)
    {
        residualGraph[i][tt[i]] += flow;
        residualGraph[tt[i]][i] -= flow;
        i = tt[i];
    }
}


int main()
{
    fin>>n>>m;
    tt.resize(n + 1);
    viz.resize(n + 1);
    residualGraph.resize(n + 1, vector<int>(n + 1, 0));
    adjList.resize(n + 1);
    int x, y, z;
    int res = 0;
    for(int i = 0; i < m; ++i)
    {
        fin>>x>>y>>z;
        residualGraph[x][y] = z;
        adjList[x].push_back(y);
        adjList[y].push_back(x);
    }

    while(bfs())
    {
        int flow = getFlow();
        res += flow;
        updateResidual(flow);

    }

    for(int i = 1; i <= n; ++i)
    {
        viz[i] = 0;
    }
    dfs(1);
    cout<<"First partition: ";
    for(int i = 1; i <= n; ++i){
        if(viz[i] == 0)
            cout<<i<<' ';
    }
    cout<<'\n';
    cout<<"Second partition: ";
    for(int i = 1; i <= n; ++i){
        if(viz[i] == 1)
            cout<<i<<' ';
    }
    cout<<'\n';

    return 0;
}