lnicola
6/24/2014 - 2:36 PM

Maximum flow

Maximum flow

4 6
1 2
1 3
2 4
3 4
4 0
4 0
5 7
1 2
1 3
1 4
2 0
3 0
4 0
5 0
0 0
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Tunnels
{
	class Program
	{
		static int r, t;
		static int[,] capacity;
		static int[,] flow;

		static void ComputeFlow(int[,] capacity, int[,] flow, int start, int stop)
		{
			while (true)
			{
				var queue = new Queue<int>();
				var visited = new bool[r + 3];
				var father = new int[r + 3];
				int x;

				for (int i = 0; i < r + 3; i++)
					father[i] = -1;

				visited[start] = true;
				queue.Enqueue(start);
				while (queue.Count > 0)
				{
					x = queue.Dequeue();
					for (int i = 0; i < r + 3; i++)
						if (capacity[x, i] > 0 && visited[i] == false)
						{
							queue.Enqueue(i);
							visited[i] = true;
							father[i] = x;
							if (i == stop)
							{
								queue.Clear();
								break;
							}
						}
				}

				if (father[stop] == -1)
					break;

				var min = int.MaxValue;
				x = stop;
				while (father[x] != -1)
				{
					if (capacity[father[x], x] < min)
						min = capacity[father[x], x];
					x = father[x];
				}

				x = stop;
				while (father[x] != -1)
				{
					capacity[father[x], x] -= min;
					capacity[x, father[x]] += min;
					flow[father[x], x] += min;
					x = father[x];
				}
			}
		}

		static void Main(string[] args)
		{
			StreamReader sr = new StreamReader(@"..\..\tunnels.in");
			int no = 0;
			while (true)
			{
				no++;
				var c = sr.ReadLine().Split(null);
				r = int.Parse(c[0]);
				t = int.Parse(c[1]);
				if (r == 0 && t == 0)
					break;
				capacity = new int[r + 3, r + 3];
				flow = new int[r + 3, r + 3];
				for (int i = 0; i < t; i++)
				{
					c = sr.ReadLine().Split(null);
					var x = int.Parse(c[0]);
					var y = int.Parse(c[1]);
					capacity[x, y]++;
					capacity[y, x]++;
				}

				int min = int.MaxValue;
				for (int current = 1; current <= r; current++)
				{
					var newCapacity = capacity.Clone() as int[,];
					var newFlow = new int[r + 3, r + 3];
					newCapacity[r + 1, 0] = 1000;
					newCapacity[0, r + 1] = 1000;
					newCapacity[r + 2, current] = 1000;
					newCapacity[current, r + 2] = 1000;

					ComputeFlow(newCapacity, newFlow, r + 1, r + 2);
					min = Math.Min(min, newFlow[r + 1, 0]);
				}
				Console.WriteLine("Case {0}: {1}", no, min);
			}
		}
	}
}