Cod sursa(job #2212530)

Utilizator felixiPuscasu Felix felixi Data 14 iunie 2018 12:57:06
Problema Critice Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.39 kb
#include <bits/stdc++.h>

using namespace std;

#define pii pair<int,int>
#define Nmax 1001
#define abs(x) ((x) > 0 ? (x) : -(x))

int n;
int father[Nmax], f[Nmax][Nmax], c[Nmax][Nmax];
vector< pii > M;
vector< int > sol, G[Nmax];
vector< bool > vis, ok1, ok2;
queue< int > Q;

bool BFS(int, vector< bool >&, bool);
void read();
void write();

int main()
{
    int cf, vf, max_flow, a, b;

    read();

    for (max_flow = 0; BFS(1, vis, true); )
    {
        for(auto &nod : G[n])
            if (vis[nod] && f[nod][n] < c[nod][n])
            {
                father[n] = nod;
                for (cf = -1, vf = n; vf != 1 && cf != 0; vf = father[vf])
                    if (cf == -1 || cf > c[father[vf]][vf] - f[father[vf]][vf])
                        cf = c[father[vf]][vf] - f[father[vf]][vf];

                if (cf > 0)
                {
                    for (vf = n; vf != 1; vf = father[vf])
                    {
                        f[father[vf]][vf] += cf;
                        f[vf][father[vf]] -= cf;
                    }

                    max_flow += cf;
                }
            }
    }

    BFS(1, ok1, false);
    BFS(n, ok2, false);

    for (int i = 0; i < static_cast<int>(M.size()); ++i)
    {
        a = M[i].first;
        b = M[i].second;

        if ((ok1[a] && ok2[b]) || (ok1[b] && ok2[a]))
            sol.push_back(i + 1);
    }

    write();

    return 0;
}


bool BFS(int vf, vector< bool > &vis, bool type)
{
    vis.assign(n + 1, false);
    vis[vf] = true;

    for (Q.push(vf); !Q.empty(); Q.pop())
    {
        vf = Q.front();

        if (vf == n && type) continue;

        for(auto &to : G[vf])
            if (!vis[to] && (type ? f[vf][to] : abs(f[vf][to])) < c[vf][to])
            {
                father[to] = vf;

                vis[to] = true;
                Q.push(to);
            }
    }

    return vis[n];
}

void read()
{
    int m, x, y, z;
    ifstream fin("critice.in");

    fin >> n;

    for (fin >> m; m; --m)
    {
        fin >> x >> y >> z;
        G[x].push_back(y);
        G[y].push_back(x);
        M.emplace_back(x, y);

        c[x][y] = c[y][x] = z;
    }

    fin.close();
}

void write()
{
    ofstream fout("critice.out");

    fout << sol.size() << '\n';
    for (auto &nod : sol) fout << nod << '\n';

    fout.close();
}