예제 #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;
        MinCostFlow minCostFlow  = new MinCostFlow();

        for (int source = 0; source < numSources; ++source)
        {
            for (int target = 0; target < numTargets; ++target)
            {
                minCostFlow.AddArcWithCapacityAndUnitCost(
                    source, /*target=*/ numSources + target, /*capacity=*/ 1,
                    /*flow unit cost=*/ costs[source, target]);
            }
        }
        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.");
        int solveStatus = minCostFlow.Solve();

        if (solveStatus == MinCostFlow.OPTIMAL)
        {
            Console.WriteLine("total computed flow cost = " +
                              minCostFlow.OptimalCost() +
                              ", expected = " + expectedCost);
        }
        else
        {
            Console.WriteLine("Solving the min cost flow problem failed." +
                              " Solver status: " + solveStatus);
        }
    }
예제 #2
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");
        }
    }
예제 #3
0
        public void PrintNetworkFlowSolution(MinCostFlow networkFlowSolution)
        {
            long optimalCost = networkFlowSolution.OptimalCost();

            Console.WriteLine("Minimum cost: " + optimalCost);
            Console.WriteLine("");
            Console.WriteLine(" Edge   Flow / Capacity  Cost");
            for (int i = 0; i < numArcs; ++i)
            {
                long cost = networkFlowSolution.Flow(i) * networkFlowSolution.UnitCost(i);
                Console.WriteLine(networkFlowSolution.Tail(i) + " -> " +
                                  networkFlowSolution.Head(i) + "  " +
                                  string.Format("{0,3}", networkFlowSolution.Flow(i)) + "  / " +
                                  string.Format("{0,3}", networkFlowSolution.Capacity(i)) + "       " +
                                  string.Format("{0,3}", cost));
            }
        }
예제 #4
0
        public long solve(CFMAStar.CostFunction costFunction)
        {
            // Independence Detection
            List <List <TimedMove> > nonConflictsPaths = null;
            IndependentDetection     id = new IndependentDetection(this.problemInstance, this.goalState);

            MAM_AgentState[] newStartPositions = id.Detect(out nonConflictsPaths);
            if (newStartPositions.Length != 0)
            {
                this.problemInstance = problemInstance.ReplanProblem(newStartPositions);
                this.reducer         = new CFMAM_MCMF_Reducer(this.problemInstance, this.goalState);
                reducer.reduce(costFunction);
                if (reducer.outputProblem == null)
                {
                    return(-1);
                }
                MinCostMaxFlow mcmfSolver = new MinCostMaxFlow(reducer.outputProblem);
                timer    = Stopwatch.StartNew();
                solution = mcmfSolver.SolveMinCostFlow();
                List <TimedMove>[] partialPlan = this.reducer.GetCFMAMSolution(this.solution, this.mcmfTime, true);
                if (costFunction == CFMAStar.CostFunction.MakeSpan)
                {
                    while (!isPathForEachAgent(partialPlan))
                    {
                        this.reducer.addNetworkLayer();
                        mcmfSolver  = new MinCostMaxFlow(reducer.outputProblem);
                        solution    = mcmfSolver.SolveMinCostFlow();
                        partialPlan = this.reducer.GetCFMAMSolution(this.solution, this.mcmfTime, true);
                    }
                }
                timer.Stop();
                this.plan         = mergePlans(partialPlan, nonConflictsPaths);
                this.mcmfTime     = timer.ElapsedMilliseconds;
                this.solutionCost = calculateCost(this.plan, costFunction);
            }
            else
            {
                this.plan         = nonConflictsPaths;
                this.solutionCost = calculateCost(this.plan, costFunction);
            }

            return(this.solutionCost);
        }
예제 #5
0
    static object Solve()
    {
        var(p, q) = Read2();
        var s  = Array.ConvertAll(new bool[p], _ => Console.ReadLine());
        var ps = Array.ConvertAll(new bool[p], _ => Read2L());
        var qs = Array.ConvertAll(new bool[q], _ => Read2L());

        var sv = p + q;
        var ev = sv + 1;
        var mf = new MinCostFlow(ev + 1);

        for (int i = 0; i < p; ++i)
        {
            mf.AddEdge(sv, i, 1, 0);
        }

        for (int j = 0; j < q; ++j)
        {
            mf.AddEdge(p + j, ev, 1, 0);
        }

        for (int i = 0; i < p; ++i)
        {
            var pa = ps[i].a - ps[i].b;
            for (int j = 0; j < q; ++j)
            {
                var qa = qs[j].a - qs[j].b;
                if (s[i][j] == '1' && pa + qa > 0)
                {
                    mf.AddEdge(i, p + j, 1, -pa - qa);
                }
            }
        }

        var r0 = ps.Sum(_ => _.b) + qs.Sum(_ => _.b);
        var r  = mf.GetMinCostForRange(sv, ev, Math.Min(p, q));

        if (r == long.MaxValue)
        {
            r = 0;
        }
        return(r0 - r);
    }
예제 #6
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;
   MinCostFlow minCostFlow = new MinCostFlow();
   for (int source = 0; source < numSources; ++source)
   {
     for (int target = 0; target < numTargets; ++target) {
       minCostFlow.AddArcWithCapacityAndUnitCost(
           source, /*target=*/numSources + target, /*capacity=*/1,
           /*flow unit cost=*/costs[source, target]);
     }
   }
   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.");
   int solveStatus = minCostFlow.Solve();
   if (solveStatus == MinCostFlow.OPTIMAL)
   {
     Console.WriteLine("total computed flow cost = " +
                       minCostFlow.OptimalCost() +
                       ", expected = " + expectedCost);
   }
   else
   {
     Console.WriteLine("Solving the min cost flow problem failed." +
                       " Solver status: " + solveStatus);
   }
 }
예제 #7
0
    static object Solve()
    {
        var(n, c) = Read2();
        var a = Read();

        var sv = 2 * n;
        var ev = sv + 1;
        var mf = new MinCostFlow(ev + 1);

        for (int i = 0; i < n; ++i)
        {
            mf.AddEdge(sv, i, 1, c);
            mf.AddEdge(n + i, ev, 1, 0);
            mf.AddEdge(i, n + i, 1, -max);

            for (int j = i + 1; j < n; j++)
            {
                mf.AddEdge(n + i, j, 1, Math.Abs(a[i] - a[j]));
            }
        }

        return(mf.GetMinCostForRange(sv, ev, n) + n * max);
    }
예제 #8
0
        public MinCostFlow SolveMinCostFlow()
        {
            // Instantiate a SimpleMinCostFlow solver.
            MinCostFlow minCostFlow = new MinCostFlow();

            // Add each arc.
            for (int i = 0; i < numArcs; ++i)
            {
                int arc = minCostFlow.AddArcWithCapacityAndUnitCost(startNodes[i], endNodes[i],
                                                                    capacities[i], unitCosts[i]);
                if (arc != i)
                {
                    throw new Exception("Internal error");
                }
            }

            // Add node supplies.
            for (int i = 0; i < numNodes; ++i)
            {
                minCostFlow.SetNodeSupply(i, supplies[i]);
            }

            // Find the min cost flow.
            int solveStatus = (int)minCostFlow.SolveMaxFlowWithMinCost();

            if (solveStatus == (int)MinCostFlow.Status.OPTIMAL)
            {
                //PrintNetworkFlowSolution(minCostFlow);
                return(minCostFlow);
            }
            else
            {
                Console.WriteLine("Solving the min cost flow problem failed. Solver status: " +
                                  solveStatus);
                return(null);
            }
        }
예제 #9
0
    static void Main()
    {
        // [START data]
        // Define four parallel arrays: sources, destinations, capacities, and unit costs
        // between each pair. For instance, the arc from node 0 to node 1 has a
        // capacity of 15.
        // Problem taken From Taha's 'Introduction to Operations Research',
        // example 6.4-2.
        int[] startNodes = { 0, 0, 1, 1, 1, 2, 2, 3, 4 };
        int[] endNodes   = { 1, 2, 2, 3, 4, 3, 4, 4, 2 };
        int[] capacities = { 15, 8, 20, 4, 10, 15, 4, 20, 5 };
        int[] unitCosts  = { 4, 4, 2, 2, 6, 1, 3, 2, 3 };

        // Define an array of supplies at each node.
        int[] supplies = { 20, 0, 0, -5, -15 };
        // [END data]

        // [START constraints]
        // Instantiate a SimpleMinCostFlow solver.
        MinCostFlow minCostFlow = new MinCostFlow();

        // Add each arc.
        for (int i = 0; i < startNodes.Length; ++i)
        {
            int arc =
                minCostFlow.AddArcWithCapacityAndUnitCost(startNodes[i], endNodes[i], capacities[i], unitCosts[i]);
            if (arc != i)
            {
                throw new Exception("Internal error");
            }
        }

        // Add node supplies.
        for (int i = 0; i < supplies.Length; ++i)
        {
            minCostFlow.SetNodeSupply(i, supplies[i]);
        }

        // [END constraints]

        // [START solve]
        // Find the min cost flow.
        MinCostFlow.Status solveStatus = minCostFlow.Solve();
        // [END solve]

        // [START print_solution]
        if (solveStatus == MinCostFlow.Status.OPTIMAL)
        {
            Console.WriteLine("Minimum cost: " + minCostFlow.OptimalCost());
            Console.WriteLine("");
            Console.WriteLine(" Edge   Flow / Capacity  Cost");
            for (int i = 0; i < minCostFlow.NumArcs(); ++i)
            {
                long cost = minCostFlow.Flow(i) * minCostFlow.UnitCost(i);
                Console.WriteLine(minCostFlow.Tail(i) + " -> " + minCostFlow.Head(i) + "  " +
                                  string.Format("{0,3}", minCostFlow.Flow(i)) + "  / " +
                                  string.Format("{0,3}", minCostFlow.Capacity(i)) + "       " +
                                  string.Format("{0,3}", cost));
            }
        }
        else
        {
            Console.WriteLine("Solving the min cost flow problem failed. Solver status: " + solveStatus);
        }
        // [END print_solution]
    }
예제 #10
0
    static void Main()
    {
        // [START solver]
        // Instantiate a SimpleMinCostFlow solver.
        MinCostFlow minCostFlow = new MinCostFlow();

        // [END solver]

        // [START data]
        // Define the directed graph for the flow.
        int[] teamA = { 1, 3, 5 };
        int[] teamB = { 2, 4, 6 };

        // Define four parallel arrays: sources, destinations, capacities, and unit costs
        // between each pair.
        int[] startNodes = { 0, 0, 11, 11, 11, 12, 12, 12, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3,
                             3, 3,  4,  4,  4,  4,  5,  5, 5, 5, 6, 6, 6, 6, 7, 8, 9, 10 };
        int[] endNodes = { 11, 12, 1, 3, 5,  2, 4, 6, 7,  8, 9, 10, 7,  8,  9, 10,  7, 8,
                           9,  10, 7, 8, 9, 10, 7, 8, 9, 10, 7,  8, 9, 10, 13, 13, 13, 13 };
        int[] capacities = { 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
                             1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
        int[] unitCosts = { 0,    0,  0,   0,  0,   0,  0,   0, 90, 76, 75, 70,  35, 85, 55, 65, 125, 95,
                            90, 105, 45, 110, 95, 115, 60, 105, 80, 75, 45, 65, 110, 95,  0,  0,   0, 0 };

        int source = 0;
        int sink   = 13;

        // Define an array of supplies at each node.
        int[] supplies = { 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -4 };
        // [END data]

        // [START constraints]
        // Add each arc.
        for (int i = 0; i < startNodes.Length; ++i)
        {
            int arc =
                minCostFlow.AddArcWithCapacityAndUnitCost(startNodes[i], endNodes[i], capacities[i], unitCosts[i]);
            if (arc != i)
            {
                throw new Exception("Internal error");
            }
        }

        // Add node supplies.
        for (int i = 0; i < supplies.Length; ++i)
        {
            minCostFlow.SetNodeSupply(i, supplies[i]);
        }
        // [END constraints]

        // [START solve]
        // Find the min cost flow.
        MinCostFlow.Status status = minCostFlow.Solve();
        // [END solve]

        // [START print_solution]
        if (status == MinCostFlow.Status.OPTIMAL)
        {
            Console.WriteLine("Total cost: " + minCostFlow.OptimalCost());
            Console.WriteLine("");
            for (int i = 0; i < minCostFlow.NumArcs(); ++i)
            {
                // Can ignore arcs leading out of source or into sink.
                if (minCostFlow.Tail(i) != 0 && minCostFlow.Tail(i) != 11 && minCostFlow.Tail(i) != 12 &&
                    minCostFlow.Head(i) != 13)
                {
                    // Arcs in the solution have a flow value of 1. Their start and end nodes
                    // give an assignment of worker to task.
                    if (minCostFlow.Flow(i) > 0)
                    {
                        Console.WriteLine("Worker " + minCostFlow.Tail(i) + " assigned to task " + minCostFlow.Head(i) +
                                          " Cost: " + minCostFlow.UnitCost(i));
                    }
                }
            }
        }
        else
        {
            Console.WriteLine("Solving the min cost flow problem failed.");
            Console.WriteLine("Solver status: " + status);
        }
        // [END print_solution]
    }
예제 #11
0
        public List <TimedMove>[] GetCFMAMSolution(MinCostFlow mcmfSolution, long mcmfTime, bool printPath = false)
        {
            Stack <NFReducerNode>[]   paths            = new Stack <NFReducerNode> [startPositions.Length];
            Stack <NFReducerNode[]>[] nodesForEachTime = new Stack <NFReducerNode[]> [this.T + 1];

            for (int i = 0; i < nodesForEachTime.Length; i++)
            {
                nodesForEachTime[i] = new Stack <NFReducerNode[]>();
            }
            // Sorting each move to it's time
            for (int i = 0; i < outputProblem.numArcs; i++)
            {
                long cost = mcmfSolution.Flow(i) * mcmfSolution.UnitCost(i);
                if (cost != 0)
                {
                    NFReducerNode fromNode = GetNode(mcmfSolution.Tail(i));
                    NFReducerNode toNode   = GetNode(mcmfSolution.Head(i));
                    if (T - fromNode.nodeTime == 0)
                    {
                        NFReducerNode[] nodesStartArray = { null, fromNode };
                        nodesForEachTime[0].Push(nodesStartArray);
                    }

                    NFReducerNode[] nodesArray = { fromNode, toNode };
                    nodesForEachTime[T - toNode.nodeTime].Push(nodesArray);
                }
            }

            // Inserting start nodes to each agent path
            int startNodesCounter = 0;

            foreach (NFReducerNode[] startNode in nodesForEachTime[0])
            {
                paths[startNodesCounter] = new Stack <NFReducerNode>();
                paths[startNodesCounter].Push(startNode[1]);
                startNodesCounter++;
            }

            // Searching agents that started on the meeting points
            for (int i = 0; i < paths.Length; i++)
            {
                if (paths[i] == null)
                {
                    if (isAgentStartedOnGoalNode())
                    {
                        paths[i] = new Stack <NFReducerNode>();
                        paths[i].Push(new NFReducerNode(0, goalState.x, goalState.y));
                    }
                    else
                    {
                        paths = paths.Where(p => p != null).ToArray();
                    }
                    break;
                }
            }

            // Adding each node of each agent to his path
            for (int i = 1; i < nodesForEachTime.Length; i++)
            {
                while (nodesForEachTime[i].Count != 0)
                {
                    NFReducerNode[] move = nodesForEachTime[i].Pop();
                    for (int j = 0; j < paths.Length; j++)
                    {
                        NFReducerNode lastNode = paths[j].Peek();
                        if (lastNode.x == move[0].x && lastNode.y == move[0].y && lastNode.nodeTime == move[0].nodeTime)
                        {
                            paths[j].Push(move[1]);
                            break;
                        }
                    }
                }
            }

            List <TimedMove>[] agentPaths = new List <TimedMove> [startPositions.Length];
            for (int i = 0; i < agentPaths.Length; i++)
            {
                agentPaths[i] = new List <TimedMove>();
            }

            for (int i = 0; i < paths.Length; i++)
            {
                int pathLength = paths[i].Count;
                while (paths[i].Count != 0)
                {
                    int           nodeTime = pathLength - paths[i].Count;
                    NFReducerNode node     = paths[i].Pop();
                    agentPaths[i].Insert(0, new TimedMove(node.x, node.y, Move.Direction.NO_DIRECTION, nodeTime));
                }
            }

            return(agentPaths);
        }