Пример #1
0
    private static void SolveMinCostFlow()
    {
        Console.WriteLine("Min Cost Flow Problem");
        int numSources = 4;
        int numTargets = 4;

        int[,] costs = { {  90,  75, 75,  80 },
                         {  35,  85, 55,  65 },
                         { 125,  95, 90, 105 },
                         {  45, 110, 95, 115 } };
        int       expectedCost = 275;
        StarGraph graph        = new StarGraph(numSources + numTargets,
                                               numSources * numTargets);
        MinCostFlow minCostFlow = new MinCostFlow(graph);

        for (int source = 0; source < numSources; ++source)
        {
            for (int target = 0; target < numTargets; ++target)
            {
                int arc = graph.AddArc(source, numSources + target);
                minCostFlow.SetArcUnitCost(arc, costs[source, target]);
                minCostFlow.SetArcCapacity(arc, 1);
            }
        }

        for (int source = 0; source < numSources; ++source)
        {
            minCostFlow.SetNodeSupply(source, 1);
        }
        for (int target = 0; target < numTargets; ++target)
        {
            minCostFlow.SetNodeSupply(numSources + target, -1);
        }
        Console.WriteLine("Solving min cost flow with " + numSources +
                          " sources, and " + numTargets + " targets.");
        if (minCostFlow.Solve())
        {
            long totalFlowCost = minCostFlow.GetOptimalCost();
            Console.WriteLine("total computed flow cost = " + totalFlowCost +
                              ", expected = " + expectedCost);
        }
        else
        {
            Console.WriteLine("No solution found");
        }
    }