Exemple #1
0
        public static void Solve()
        {
            var(N, M) = Scanner.Scan <int, int>();
            var G = new string[N];

            for (var i = 0; i < N; i++)
            {
                G[i] = Scanner.Scan <string>();
            }
            var       mcfg = new MinCostFlowGraph(N * M + 2);
            var       s    = N * M;
            var       t    = N * M + 1;
            var       sum  = 0;
            const int Inf  = (int)1e9;

            for (var i = 0; i < N; i++)
            {
                for (var j = 0; j < M; j++)
                {
                    if (G[i][j] == '#')
                    {
                        continue;
                    }
                    var dist = N - i + M - j;
                    if (G[i][j] == 'o')
                    {
                        mcfg.AddEdge(s, i * M + j, 1, 0);
                        sum += dist;
                    }
                    mcfg.AddEdge(i * M + j, t, 1, dist);
                    if (i + 1 < N && G[i + 1][j] != '#')
                    {
                        mcfg.AddEdge(i * M + j, (i + 1) * M + j, Inf, 0);
                    }
                    if (j + 1 < M && G[i][j + 1] != '#')
                    {
                        mcfg.AddEdge(i * M + j, i * M + (j + 1), Inf, 0);
                    }
                }
            }

            var answer = sum - mcfg.Flow(s, t, Inf).Item2;

            Console.WriteLine(answer);
        }
Exemple #2
0
        public static void Solve()
        {
            var(N, K) = Scanner.Scan <int, int>();
            var A    = new long[N][].Select(x => Scanner.ScanEnumerable <long>().ToArray()).ToArray();
            var mcfg = new MinCostFlowGraph(N * 2 + 2);
            var s    = N * 2;
            var t    = N * 2 + 1;
            var inf  = (long)1e9;

            mcfg.AddEdge(s, t, N * K, inf);
            for (var i = 0; i < N; i++)
            {
                mcfg.AddEdge(s, i, K, 0);
                mcfg.AddEdge(N + i, t, K, 0);
            }

            for (var i = 0; i < N; i++)
            {
                for (var j = 0; j < N; j++)
                {
                    mcfg.AddEdge(i, N + j, 1, inf - A[i][j]);
                }
            }
            var result = mcfg.FlowOf(s, t, N * K);

            Console.WriteLine(inf * N * K - result.Item2);

            var G = new char[N][].Select(x => Enumerable.Repeat('.', N).ToArray()).ToArray();

            foreach (var edge in mcfg.GetEdges().Where(x => x.From != s && x.To != t && x.Flow != 0))
            {
                G[edge.From][edge.To - N] = 'X';
            }

            Console.WriteLine(string.Join("\n", G.Select(x => new string(x))));
        }