Cod sursa(job #3332270)

Utilizator GabiRB1Rafael GabiRB1 Data 5 ianuarie 2026 20:03:06
Problema Algola Scor 60
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 2.26 kb
#include <bits/stdc++.h>
using namespace std;

int cap[2555][2555];
int src = 0, dest = 2554, add = 2504, pas = 50, n, m, p[55];
struct muchie
{
    int x, y, c;
};vector <muchie> M;

int bfs(int src, int dest, vector <int> &parent)
{
    for(int i = src; i <= dest; i ++)
        parent[i] = -1;
    parent[src] = -2;
    deque <pair<int, int>> q;
    q.push_back({src, 1e9});
    int minn = 1e9;
    while(!q.empty())
    {
        int nod = q.front().first, flow = q.front().second;
        q.pop_front();
        for(int i = src; i <= dest; i ++)
        {
            if(parent[i] == -1 && cap[nod][i] > 0)
            {
                parent[i] = nod;
                int new_flow = min(flow, cap[nod][i]);
                if(dest == i)
                    return new_flow;
                q.push_back({i, new_flow});
            }
        }
    }
    return 0;

}
int max_flow(int src, int dest)
{
    int flow = 0, new_flow;
    vector<int> parent(dest + 5);
    while(new_flow = bfs(src, dest, parent))
    {
        flow += new_flow;
        int nod = dest;
        while(nod != src)
        {
            int t = parent[nod];
            cap[t][nod] -= new_flow;
            cap[nod][t] += new_flow;
            nod = t;
        }
    }
    return flow;
}
int main()
{
    ifstream f("algola.in");
    ofstream g("algola.out");
    f >> n >> m;
    int total = 0;
    for(int i = 1; i <= n; i ++)
        f >> p[i], total += p[i], cap[src][i] = p[i];
    for(int i = 1; i <= m; i ++)
    {
        int x, y, c;
        f >> x >> y >> c;
        M.push_back({x, y, c});
        //cap[x + add][y + add] = c;
       // cap[y + add][x + add] = c;
    }
    cap[1][dest] = 1e9;
    int k = 0;
    int flow = max_flow(src, dest);
    while(flow != total)
    {
        int oldB = k * pas;
        int newB = (k + 1) * pas;
        k ++;
        for(int i = 1; i <= n; i ++)
            cap[oldB + i][newB + i] = 1e9;

        for(int i = 0; i < m; i ++)
        {
            int x = M[i].x, y = M[i].y, c = M[i].c;
            cap[x + oldB][y + newB] = c;
            cap[y + oldB][x + newB] = c;
        }
        cap[newB + 1][dest] = 1e9;
        flow += max_flow(src, dest);
    }
    g << k;


    return 0;
}