Cod sursa(job #1936725)

Utilizator radu.leonardoThe Doctor radu.leonardo Data 23 martie 2017 12:50:37
Problema Critice Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.78 kb
#include <bits/stdc++.h>
#define maxN 1002
FILE *fin  = freopen("critice.in", "r", stdin);
FILE *fout = freopen("critice.out", "w", stdout);
using namespace std;
vector < pair<int,int> > Edges;
queue <int> Q;
int N, M, r[maxN][maxN],flow;
bool pathFirst[maxN]= {0},pathLast[maxN]= {0};

struct Node
{
    int dad;
    vector <int> adj;
} G[maxN];

void read()
{
    int u, v, capacity;
    scanf("%d %d", &N, &M);
    for(int i = 0; i < M; ++ i)
    {
        scanf("%d %d %d", &u, &v, &capacity);
        Edges.push_back(make_pair(u,v));
        G[u].adj.push_back(v);
        G[v].adj.push_back(u);
        r[u][v] = capacity;
        r[v][u] = capacity;
    }
}

int BFS()
{
    for(int i = 1; i <= N; ++ i)   G[i].dad = 0;
    Q.push(1);
    G[1].dad = 1;
    while(!Q.empty())
    {
        int node = Q.front();
        Q.pop();
        for(int i=0; i<G[node].adj.size(); i++ )
        {
            int son=G[node].adj[i];
            if(r[node][son] == 0 || G[son].dad) continue;
            if(son != N) Q.push(son);
            G[son].dad = node;
        }
    }
    return G[N].dad != 0;
}

void maxflow()
{
    while(BFS())
    {
        for(int i=0; i<G[N].adj.size(); i++ )
        {
            int node=G[N].adj[i];
            if(G[node].dad)
            {
                G[N].dad = node;
                int pathFlow = 0x7fffffff;
                node = N;
                while(node != 1)
                {
                    pathFlow = min(pathFlow, r[G[node].dad][node]);
                    node = G[node].dad;
                }
                node = N;
                while(node != 1)
                {
                    r[G[node].dad][node] -= pathFlow;
                    r[node][G[node].dad] += pathFlow;
                    node = G[node].dad;
                }
                flow += pathFlow;
            }
        }
    }
}

void BFS2(int s,bool viz[])
{
    viz[s]=1;
    Q.push(s);
    while(!Q.empty())
    {
        int nod=Q.front();
        for(int i=0; i<G[nod].adj.size(); ++i)
        {
            int x=G[nod].adj[i];
            if(!viz[x]&&r[nod][x]>0&&r[x][nod])
            {
                viz[x]=1;
                Q.push(x);
            }
        }
        Q.pop();
    }
}

void solve()
{
    int sol=0;
    BFS2(1,pathFirst);
    BFS2(N,pathLast);
    for(int i=0; i<Edges.size(); ++i)
        if((pathFirst[Edges[i].first]&&pathLast[Edges[i].second])||(pathFirst[Edges[i].second]&&pathLast[Edges[i].first])) ++sol;
    cout<<sol<<'\n';
    for(int i=0; i<Edges.size(); ++i)
        if((pathFirst[Edges[i].first]&&pathLast[Edges[i].second])||(pathFirst[Edges[i].second]&&pathLast[Edges[i].first])) cout<<i+1<<'\n';
}
int main()
{
    read();
    maxflow();
    solve();
}