Cod sursa(job #2699379)

Utilizator PredescuSebastianIonPredescu Sebastian Ion PredescuSebastianIon Data 24 ianuarie 2021 12:40:16
Problema Critice Scor 100
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.41 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

#define INF 1e9

using namespace std;

int n, m;
vector<vector<int>> residual;
vector<bool> visited;
vector<vector<int>> v;
vector<int> path;
vector<pair<int,int>> vertices;

bool bfs()
{
    queue<int> q;
    for(auto &p: path)
        p = 0;
    q.emplace(1);
    path[1] = -1;
    while(!q.empty() && !path[n])
    {
        int current = q.front();
        q.pop();
        if(current==n) continue;
        for(auto &node: v[current])
            if(residual[current][node] && !path[node])
            {
                path[node] = current;
                q.emplace(node);
            }
    }
    return path[n] != 0;
}

void edmonds_karp()
{
    path.resize(n+1, 0);
    while(bfs())
    {
        for(auto &node: v[n])
            if(path[node]!=0 && residual[node][n])
            {
                int current = n;
                path[current] = node;
                int flow = INF;
                while(path[current]!=-1)
                {
                    flow = min(flow, residual[path[current]][current]);
                    current = path[current];
                }
                if(!flow) continue;
                current = n;
                while(path[current]!=-1)
                {
                    residual[path[current]][current] -= flow;
                    residual[current][path[current]] += flow;
                    current = path[current];
                }
            }
    }
}

void dfs(int node1)
{
    visited[node1] = true;
    for(auto &node2: v[node1])
        if(!visited[node2] && residual[node1][node2])
            dfs(node2);
}

int main()
{
    ifstream fin("critice.in");
    ofstream fout("critice.out");
    fin>>n>>m;
    residual.resize(n+1, vector<int>(n+1, 0));
    v.resize(n+1);
    while(m--)
    {
        int x, y, c;
        fin>>x>>y>>c;
        v[x].emplace_back(y);
        v[y].emplace_back(x);
        residual[x][y] = c;
        residual[y][x] = c;
        vertices.emplace_back(x, y);
    }
    edmonds_karp();
    visited.resize(n+1, false);
    dfs(1);
    vector<int> ans;
    for(int i=0; i<vertices.size(); ++i)
        if(visited[vertices[i].first]!=visited[vertices[i].second])
            ans.emplace_back(i+1);
    fout<<ans.size()<<'\n';
    for(auto &a: ans)
        fout<<a<<'\n';
    return 0;
}