Cod sursa(job #1689440)

Utilizator Cristian1997Vintur Cristian Cristian1997 Data 14 aprilie 2016 11:19:12
Problema Critice Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.4 kb
using namespace std;
#include <fstream>
#include <vector>
#include <algorithm>
#include <string>
#include <queue>
using 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 isCritic(int, int);
bool BFS(int);
void read();
void write();

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

	read();

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

	for (int i = 0; i < static_cast<int>(M.size()); ++i)
		if (isCritic(M[i].first, M[i].second))
			sol.push_back(i + 1);

	write();

    return 0;
}

bool isCritic(int a, int b)
{
	int vf;

	ok1.assign(n + 1, false);
	ok1[1] = true;

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

		for (auto &to : G[vf])
			if (!ok1[to] && abs(f[vf][to]) < c[vf][to])
			{
				ok1[to] = true;
				Q.push(to);
			}
	}

	ok2.assign(n + 1, false);
	ok2[n] = true;

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

		for (auto &to : G[vf])
			if (!ok2[to] && abs(f[vf][to]) < c[vf][to])
			{
				ok2[to] = true;
				Q.push(to);
			}
	}

	return (ok1[a] && ok2[b]) || (ok1[b] && ok2[a]);
}

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

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

		if (vf == n) continue;

		for(auto &to : G[vf])
			if (!vis[to] && 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();
}