Exemplo n.º 1
0
        public static FlowNetwork BuildComplexFlowNetwork()
        {
            Graph g = new Graph();

            g.AddEdge("s", "a");
            g.AddEdge("s", "b");
            g.AddEdge("a", "c");
            g.AddEdge("b", "a");
            g.AddEdge("b", "c");
            g.AddEdge("c", "d");
            g.AddEdge("c", "t");
            g.AddEdge("d", "b");
            g.AddEdge("d", "t");
            var dictC = new Dictionary <EdgeKey, int>();

            dictC[g.GetEdge("s", "a").GetKey()] = 4;
            dictC[g.GetEdge("s", "b").GetKey()] = 8;
            dictC[g.GetEdge("a", "c").GetKey()] = 6;
            dictC[g.GetEdge("b", "a").GetKey()] = 3;
            dictC[g.GetEdge("b", "c").GetKey()] = 6;
            dictC[g.GetEdge("c", "d").GetKey()] = 3;
            dictC[g.GetEdge("c", "t").GetKey()] = 11;
            dictC[g.GetEdge("d", "b").GetKey()] = 1;
            dictC[g.GetEdge("d", "t").GetKey()] = 2;
            var c = FlowNetwork.DictToFlow(dictC);

            return(new FlowNetwork(g, c, "s", "t"));
        }
Exemplo n.º 2
0
        private bool HasAugmentingPath(FlowNetwork graph, int s, int t)
        {
            _edgeTo = new Dictionary <int, FlowEdge>();
            _marked = new HashSet <int>();

            var queue = new Queue <int>();

            queue.Enqueue(s);

            _marked.Add(s);

            while (queue.Count > 0)
            {
                var v = queue.Dequeue();

                foreach (var edge in graph.Adjacent(v))
                {
                    var w = edge.Other(v);

                    if (edge.ResidualCapacityTo(w) > 0 && !_marked.Contains(w))
                    {
                        _edgeTo.Add(w, edge);
                        _marked.Add(w);

                        queue.Enqueue(w);
                    }
                }
            }

            return(_marked.Contains(t));
        }
 public virtual void SetGraph(FlowNetwork g)
 {
     graph = new FlowNetwork(g);
     graph.OnEdgeFlowChanged += (sender, edge) => OnEdgeFlowChanged?.Invoke(this, sender, edge);
     graph.OnEdgeMarked      += (sender, edge) => OnEdgeMarked?.Invoke(this, sender, edge);
     graph.OnEdgeUnmarked    += (sender, edge) => OnEdgeUnmarked?.Invoke(this, sender, edge);
 }
        public void RedirectEdge(FlNwNodeVisualization _to_node, bool _rerout_start, FlowNetwork _owner)
        {
            if (_to_node == null || _owner == null)
            {
                return;
            }

            // perform redirection in the data
            FlNetEdge edge_data = this.FN_Edge;
            FlNetNode node_data = _to_node.FN_Node;
            bool      success   = false;

            if (edge_data != null && node_data != null)
            {
                success = _owner.RedirectEdge(edge_data, _rerout_start, node_data);
            }

            // perform redirection in the visualizations
            if (success)
            {
                if (_rerout_start)
                {
                    this.StartVis = _to_node;
                }
                else
                {
                    this.EndVis = _to_node;
                }
            }
        }
Exemplo n.º 5
0
        private static void TestResidualNetwork()
        {
            //Create graph from Figure 6.10
            FlowNetwork fn = new FlowNetwork();
            Vertex      v1 = new Vertex();
            Vertex      v2 = new Vertex();
            Vertex      v3 = new Vertex();
            Vertex      v4 = new Vertex();

            fn.AddVertex(v1);
            fn.AddVertex(v2);
            fn.AddVertex(v3);
            fn.AddVertex(v4);

            fn.SetSource(v1);
            fn.SetSink(v4);

            fn.AddEdge(new FlowEdge(v1, v3, 3, 4));
            fn.AddEdge(new FlowEdge(v1, v2, 2, 2));
            fn.AddEdge(new FlowEdge(v2, v3, 2, 3));
            fn.AddEdge(new FlowEdge(v3, v4, 5, 5));
            fn.AddEdge(new FlowEdge(v2, v4, 0, 1));

            Graph g = GraphAlgorithms.CreateResidualNetwork(fn);
        }
Exemplo n.º 6
0
        private static void TestMaxFlow()
        {
            FlowNetwork fn = new FlowNetwork();

            Vertex v1 = new Vertex();
            Vertex v2 = new Vertex();
            Vertex v3 = new Vertex();
            Vertex v4 = new Vertex();
            Vertex v5 = new Vertex();
            Vertex v6 = new Vertex();

            fn.AddVertex(v1);
            fn.AddVertex(v2);
            fn.AddVertex(v3);
            fn.AddVertex(v4);
            fn.AddVertex(v5);
            fn.AddVertex(v6);

            fn.SetSource(v1);
            fn.SetSink(v6);

            fn.AddEdge(new FlowEdge(v1, v2, 0f, 2f));
            fn.AddEdge(new FlowEdge(v1, v3, 0f, 2f));
            fn.AddEdge(new FlowEdge(v2, v4, 0f, 2f));
            fn.AddEdge(new FlowEdge(v3, v4, 1f, 2f));
            fn.AddEdge(new FlowEdge(v3, v5, 0f, 2f));
            fn.AddEdge(new FlowEdge(v4, v6, 1f, 2f));
            fn.AddEdge(new FlowEdge(v5, v6, 0f, 2f));

            //float maxFlow = GraphAlgorithms.MaximumFlow(fn);

            //Console.WriteLine("Max flow is " + maxFlow);
        }
Exemplo n.º 7
0
    public FordFulkerson(FlowNetwork G, int s, int t)
    {
        Validate(s, G.V);
        Validate(t, G.V);
        if (s == t)
        {
            throw new ArgumentException("Source equals sink");
        }
        if (!IsFeasible(G, s, t))
        {
            throw new ArgumentException("Initial flow is infeasible");
        }

        Value = Excess(G, t);
        while (HasAugmentingPath(G, s, t))
        {
            var bottle = Double.PositiveInfinity;

            // compute bottleneck capacity;
            for (var v = t; v != s; v = _edgeTo[v].Other(v))
            {
                bottle = Math.Min(bottle, _edgeTo[v].ResidualCapacityTo(v));
            }

            // augment flow
            for (var v = t; v != s; v = _edgeTo[v].Other(v))
            {
                _edgeTo[v].AddResidualFlowTo(v, bottle);
            }

            Value += bottle;
        }
    }
Exemplo n.º 8
0
 private void mnOpen_Click(object sender, EventArgs e)
 {
     if (dlgOpenFile.ShowDialog() == DialogResult.OK)
     {
         using (FileStream fs = new FileStream(dlgOpenFile.FileName, FileMode.Open))
         {
             XmlDocument xml = new XmlDocument();
             try
             {
                 xml.Load(fs);
                 FlowNetwork g = new FlowNetwork();
                 g.ParseXml(xml);
                 Runtime.currentGraph = g;
                 Visualizer.ZoomFit(pbDraw.ClientRectangle);
                 Invalidate();
                 pbDraw.Invalidate();
             }
             catch (Exception ex)
             {
                 Log.Write("Can't load FlowNetwork from file.", Log.ERROR);
                 Log.Write(ex.Message, Log.ERROR);
             }
         }
     }
 }
Exemplo n.º 9
0
    private bool HasAugmentingPath(FlowNetwork G, int s, int t)
    {
        _edgeTo = new FlowEdge[G.V];
        _marked = new bool[G.V];

        var queue = new Queue <int>();

        queue.Enqueue(s);
        _marked[s] = true;
        while (queue.Count > 0 && !_marked[t])
        {
            var v = queue.Dequeue();

            foreach (var e in G.Adj(v))
            {
                var w = e.Other(v);

                if (e.ResidualCapacityTo(w) > 0)
                {
                    if (!_marked[w])
                    {
                        _edgeTo[w] = e;
                        _marked[w] = true;
                        queue.Enqueue(w);
                    }
                }
            }
        }

        return(_marked[t]);
    }
Exemplo n.º 10
0
        public void Test()
        {
            FlowNetwork network = GraphGenerator.flowNetwork();

            FordFulkerson fordFulkerson = new FordFulkerson(network, 0, 7);

            console.WriteLine("max-flow: " + fordFulkerson.Value);
            Console.WriteLine("max-flow: " + fordFulkerson.Value);
        }
        public FlowNetworkGraphWindow OpenNetworkGraphWindow(FlowNetwork _to_display, ComponentFactory _factory)
        {
            this.flow_nw_Gr_win             = new FlowNetworkGraphWindow();
            this.flow_nw_Gr_win.Network     = _to_display;
            this.flow_nw_Gr_win.CompManager = _factory;
            this.flow_nw_Gr_win.Show();

            return(this.flow_nw_Gr_win);
        }
Exemplo n.º 12
0
        private FlowNetwork FromFn(FileInfo file)
        {
            FlowNetwork g = new FlowNetwork();
            int         source = -1, target = -1;

            try
            {
                System.IO.StreamReader fs =
                    new System.IO.StreamReader(file.FullName);
                string line;
                while ((line = fs.ReadLine()) != null)
                {
                    if (line.StartsWith("SOURCE"))
                    {
                        var s = line.Split(':');
                        source = int.Parse(s[1]) - 1;
                    }
                    if (line.StartsWith("TARGET"))
                    {
                        var s = line.Split(':');
                        target = int.Parse(s[1]) - 1;
                    }
                    if (char.IsLetter(line[0]))
                    {
                        continue;
                    }
                    var d  = line.Split(new char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
                    int n0 = int.Parse(d[0]) - 1; // My numbering starts with 0, not 1
                    if (n0 == -2)
                    {
                        break;
                    }
                    int n1 = int.Parse(d[1]) - 1; // My numbering starts with 0, not 1
                    int w  = int.Parse(d[2]);     // weight
                    g.AddEdge(n0, n1, w);
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex.Message, Log.ERROR);
            }

            g.Source = source;
            g.Target = target;
            var validation = g.Validate();

            if (validation.Count > 0)
            {
                foreach (var error in validation)
                {
                    Log.Write(error, Log.ERROR);
                }
                return(null);
            }
            return(g);
        }
Exemplo n.º 13
0
        private void onNewFlowNetwork(object sender, EventArgs e)
        {
            string graphName = "Graph " + graphCounter;

            FlowNetwork newGraph = app.NewFlowNetwork(graphName);

            newGraph.ShowEdgeLabels = true;

            makeNewGraphPanel(newGraph);
        }
Exemplo n.º 14
0
        private FlowNetwork FromDimac(FileInfo file)
        {
            FlowNetwork g   = new FlowNetwork();
            var         srs = -1;
            var         trg = -1;

            try
            {
                System.IO.StreamReader fs =
                    new System.IO.StreamReader(file.FullName);
                string line;
                while ((line = fs.ReadLine()) != null)
                {
                    if (line.EndsWith("s"))
                    {
                        var s = line.Split(' ');
                        srs = int.Parse(s[1]) - 1;
                    }
                    if (line.EndsWith("t"))
                    {
                        var t = line.Split(' ');
                        trg = int.Parse(t[1]) - 1;
                    }
                    if (line.StartsWith("a"))
                    {
                        var a    = line.Split(' ');
                        int from = int.Parse(a[1]) - 1;

                        int to     = int.Parse(a[2]) - 1;
                        int weight = int.Parse(a[3]);
                        g.AddEdge(from, to, weight);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Write(ex.Message, Log.ERROR);
            }
            g.Source = srs;
            g.Target = trg;
            var validation = g.Validate();

            if (validation.Count > 0)
            {
                foreach (var error in validation)
                {
                    Log.Write(error, Log.ERROR);
                }
                return(null);
            }
            return(g);
        }
Exemplo n.º 15
0
        private FlowNetwork FromCSV(FileInfo file)
        {
            FlowNetwork g = new FlowNetwork();
            int         source = -1, target = -1;

            using (TextFieldParser parser = new TextFieldParser(file.FullName))
            {
                parser.TextFieldType = FieldType.Delimited;
                parser.SetDelimiters(",");
                int line = 0;
                while (!parser.EndOfData)
                {
                    string[] fields = parser.ReadFields();
                    line++;
                    if (line == 1)
                    {
                        //skip header
                        continue;
                    }

                    if (line == 2)
                    {
                        int.TryParse(fields[0], out source);
                        int.TryParse(fields[1], out target);
                        //parse source and target
                        continue;
                    }
                    //Process row

                    int    from, to;
                    double capacity;
                    int.TryParse(fields[0], out from);
                    int.TryParse(fields[1], out to);
                    double.TryParse(fields[2], out capacity);
                    g.AddEdge(from, to, capacity);
                }
            }
            g.Source = source;
            g.Target = target;
            var validation = g.Validate();

            if (validation.Count > 0)
            {
                foreach (var error in validation)
                {
                    Log.Write(error, Log.ERROR);
                }
                return(null);
            }
            return(g);
        }
Exemplo n.º 16
0
        public void TestDinitz()
        {
            FlowNetwork N = BuildSimpleFlowNetwork();
            var         f = N.Dinitz();

            Assert.AreEqual(1, f(N.G.GetEdge("s", "a")));
            Assert.AreEqual(1, f(N.G.GetEdge("s", "b")));
            Assert.AreEqual(1, f(N.G.GetEdge("a", "t")));
            Assert.AreEqual(1, f(N.G.GetEdge("b", "t")));
            Assert.IsTrue(N.IsValidFlow(f));

            N = BuildComplexFlowNetwork();
            f = N.Dinitz();
            Assert.AreEqual(12, f(N.G.GetEdge("s", "a")) + f(N.G.GetEdge("s", "b")));
            Assert.AreEqual(12, f(N.G.GetEdge("c", "t")) + f(N.G.GetEdge("d", "t")));
            Assert.IsTrue(N.IsValidFlow(f));
        }
Exemplo n.º 17
0
    private double Excess(FlowNetwork G, int v)
    {
        var excess = 0.0;

        foreach (var e in G.Adj(v))
        {
            if (v == e.From)
            {
                excess -= e.Flow;
            }
            else
            {
                excess += e.Flow;
            }
        }
        return(excess);
    }
Exemplo n.º 18
0
    private bool IsFeasible(FlowNetwork G, int s, int t)
    {
        for (var v = 0; v < G.V; v++)
        {
            foreach (var e in G.Adj(v))
            {
                if (e.Flow < Double.Epsilon || e.Flow > e.Capacity + Double.Epsilon)
                {
                    // Sytem.err.println("Edge does not satisfy capacity constraints: " + e);
                    return(false);
                }
            }
        }

        if (Math.Abs(Value + Excess(G, s)) > Double.Epsilon)
        {
            // System.err.println("Excess at source = " + Excess(G, s));
            // System.err.println("Mas flow = " + Value);
            return(false);
        }

        if (Math.Abs(Value - Excess(G, t)) > Double.Epsilon)
        {
            //System.err.println("Excess at sink   = " + excess(G, t));
            //System.err.println("Max flow         = " + value);
            return(false);
        }

        for (int v = 0; v < G.V; v++)
        {
            if (v == s || v == t)
            {
                continue;
            }

            if (Math.Abs(Excess(G, v)) > Double.Epsilon)
            {
                //System.err.println("Net flow out of " + v + " doesn't equal zero");
                return(false);
            }
        }

        return(true);
    }
Exemplo n.º 19
0
 private double DFS(ref FlowNetwork graph, ref List <FlowEdge> path, int[] ptr, int dest, int u, double f)
 {
     if (u == dest)
     {
         return(f);
     }
     for (; ptr[u] < graph.Nodes[u].OutcomingEdges.Count(); ++ptr[u])
     {
         FlowEdge e = graph.Nodes[u].OutcomingEdges[ptr[u]];
         if (e.Flow < e.Capacity)
         {
             double df = DFS(ref graph, ref path, ptr, dest, e.To, Math.Min(f, e.Capacity - e.Flow));
             if (df > 0)
             {
                 path.Add(e);
                 return(df);
             }
         }
     }
     return(0);
 }
Exemplo n.º 20
0
        public FordFulkerson(FlowNetwork graph, int s, int t)
        {
            Value = 0;

            while (HasAugmentingPath(graph, s, t))
            {
                var bottle = double.PositiveInfinity;

                for (var v = t; v != s; v = _edgeTo[v].Other(v))
                {
                    bottle = Math.Min(bottle, _edgeTo[v].ResidualCapacityTo(v));
                }

                for (var v = t; v != s; v = _edgeTo[v].Other(v))
                {
                    _edgeTo[v].AddResidualFlowTo(v, bottle);
                }

                Value += bottle;
            }
        }
Exemplo n.º 21
0
        public static FlowNetwork flowNetwork()
        {
            FlowNetwork g = new FlowNetwork(8);

            g.addEdge(new FlowEdge(0, 1, 10));
            g.addEdge(new FlowEdge(0, 2, 5));
            g.addEdge(new FlowEdge(0, 3, 15));
            g.addEdge(new FlowEdge(1, 4, 9));
            g.addEdge(new FlowEdge(1, 5, 15));
            g.addEdge(new FlowEdge(1, 2, 4));
            g.addEdge(new FlowEdge(2, 5, 8));
            g.addEdge(new FlowEdge(2, 3, 4));
            g.addEdge(new FlowEdge(3, 6, 16));
            g.addEdge(new FlowEdge(4, 5, 15));
            g.addEdge(new FlowEdge(4, 7, 10));
            g.addEdge(new FlowEdge(5, 7, 10));
            g.addEdge(new FlowEdge(5, 6, 15));
            g.addEdge(new FlowEdge(6, 2, 6));
            g.addEdge(new FlowEdge(6, 7, 10));

            return(g);
        }
Exemplo n.º 22
0
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            if (container == null)
            {
                return(null);
            }
            FrameworkElement element = container as FrameworkElement;

            if (element == null)
            {
                return(null);
            }

            if (item == null)
            {
                return(element.TryFindResource("DT_Empty") as DataTemplate);
            }

            FlNetNode   node    = item as FlNetNode;
            FlNetEdge   edge    = item as FlNetEdge;
            FlowNetwork network = item as FlowNetwork;

            if (node != null && network == null)
            {
                return(element.TryFindResource("FlNetNodeInList") as DataTemplate);
            }
            else if (edge != null)
            {
                return(element.TryFindResource("FlNetEdgeInList") as DataTemplate);
            }
            else if (network != null)
            {
                return(element.TryFindResource("NetworkInList") as DataTemplate);
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 23
0
        private void onMaxFlow(object sender, EventArgs e)
        {
            if (CurrentGraphPanel == null)
            {
                return;
            }

            //Make sure one vertex is selected
            List <ISelectable> selection = CurrentGraphPanel.GetSelection();
            GUIVertex          source, sink;

            if (selection.Count != 2)
            {
                Output.WriteLine("Please select both the source and the sink, in that order");
                return;
            }
            else if (selection[0] as GUIVertex == null || selection[1] as GUIVertex == null)
            {
                Output.WriteLine("Please select both the source and the sink, in that order");
                return;
            }
            else
            {
                source = selection[0] as GUIVertex;
                sink   = selection[1] as GUIVertex;
            }

            List <GUIVertex> verts = CurrentGraphPanel.Vertices;
            FlowNetwork      fn    = CurrentGraphPanel.Graph as FlowNetwork;

            if (fn != null)
            {
                float max = GraphAlgorithms.MaximumFlow(fn, fn.GetVertices().IndexOf(source.Vertex), fn.GetVertices().IndexOf(sink.Vertex));
                Output.WriteLine("[Max Flow Output]");
                Output.WriteLine("Max flow is " + max);
                Output.WriteLine("[End Max Flow Output]");
            }
        }
    /**//**/ public static void main(string[] strarr)
    {
        int         num         = Integer.parseInt(strarr[0]);
        int         num2        = Integer.parseInt(strarr[1]);
        int         i           = 2 * num;
        int         i2          = 2 * num + 1;
        FlowNetwork flowNetwork = new FlowNetwork(2 * num + 2);

        for (int j = 0; j < num2; j++)
        {
            int k    = StdRandom.uniform(num);
            int num3 = StdRandom.uniform(num) + num;
            flowNetwork.addEdge(new FlowEdge(k, num3, double.PositiveInfinity));
            StdOut.println(new StringBuilder().append(k).append("-").append(num3).toString());
        }
        for (int j = 0; j < num; j++)
        {
            flowNetwork.addEdge(new FlowEdge(i, j, (double)1f));
            flowNetwork.addEdge(new FlowEdge(j + num, i2, (double)1f));
        }
        FordFulkerson fordFulkerson = new FordFulkerson(flowNetwork, i, i2);

        StdOut.println();
        StdOut.println(new StringBuilder().append("Size of maximum matching = ").append(ByteCodeHelper.d2i(fordFulkerson.value())).toString());
        for (int k = 0; k < num; k++)
        {
            Iterator iterator = flowNetwork.adj(k).iterator();
            while (iterator.hasNext())
            {
                FlowEdge flowEdge = (FlowEdge)iterator.next();
                if (flowEdge.from() == k && flowEdge.flow() > (double)0f)
                {
                    StdOut.println(new StringBuilder().append(flowEdge.from()).append("-").append(flowEdge.to()).toString());
                }
            }
        }
    }
Exemplo n.º 25
0
 // assumes that _fn_nw is not NULL
 public FlNwNetworkVisualization(FlowNwGraph _parent, FlowNetwork _fn_nw, NodePosInFlow _pos_in_flow)
     : base(_parent, _fn_nw, _pos_in_flow)
 {
     this.fn_nw = _fn_nw;
 }
Exemplo n.º 26
0
        private void ExtendFlow(ref FlowNetwork A, List <List <int> > scc, double flow, List <FlowEdge> path)
        {
            var supernodes = new List <int>();

            foreach (var contracted in scc.Where((list) => list.Count() > 1))
            {
                supernodes.Add(contracted.First());
            }

            var excess = new Dictionary <int, double>(); //flow balance

            foreach (var node in graph.Nodes.Keys)
            {
                excess.Add(node, 0);
            }
            excess[graph.Source] = flow;  //should be 0 at the end of routing flow
            excess[graph.Target] = -flow; //should be 0 at the end of routing flow

            foreach (var edge in path)
            {
                if (!supernodes.Contains(edge.From) && !supernodes.Contains(edge.To))
                {
                    graph.PushFlow(edge.From, edge.To, flow);
                    excess[edge.From] -= flow;
                    excess[edge.To]   += flow;
                }
            }
            //reroute flow in strongly connected components using excess lables
            //working with original graph
            foreach (var contracted in scc.Where((list) => list.Count() > 1))
            {
                foreach (var node in contracted) //routing edges in and out of supernodes
                {
                    foreach (var edge in graph.Nodes[node].IncomingEdges)
                    {
                        if (excess[edge.From] > 0 && !contracted.Contains(edge.From))
                        {
                            var f = Math.Min(edge.ResidualCapacityTo(node), excess[edge.From]);
                            edge.AddFlow(f, node);
                            excess[edge.From] -= f;
                            excess[node]      += f;
                        }
                    }
                    foreach (var edge in graph.Nodes[node].OutcomingEdges)
                    {
                        if (excess[edge.To] < 0 && !contracted.Contains(edge.To))
                        {
                            var f = Math.Min(edge.ResidualCapacityTo(edge.To), -excess[edge.To]);
                            edge.AddFlow(f, edge.To);
                            excess[node]    -= f;
                            excess[edge.To] += f;
                        }
                    }
                }
                while (contracted.Count((id) => excess[id] > 0) > 0)//multiple source
                {
                    int srs = contracted.First((id) => excess[id] > 0);
                    while (excess[srs] > 0 && contracted.Count((id) => excess[id] < 0) > 0) //multiple target
                    {
                        int trg = contracted.First((id) => excess[id] < 0);
                        SimpleBlockingFlowInConnectedComponent(contracted, ref excess, srs, trg);
                    }
                }
            }
        }
Exemplo n.º 27
0
        private FlowNetwork ContractZeroLengthSCC(out List <List <int> > scc)
        {
            int[] ids      = new int[graph.NodeCount];
            int[] lowLinks = new int[graph.NodeCount];

            var admissible_edges = new List <FlowEdge>();

            foreach (var edge in graph.Edges)
            {
                if (dist[edge.From] == dist[edge.To] + BinaryLength(edge))//length[edge]) //admissible edge
                {
                    admissible_edges.Add(edge);
                }
            }

            scc = new List <List <int> >();
            var stack        = new Stack <int>();
            var sorted_nodes = TopologicalSort(admissible_edges);

            // поиск сильно связанных компонентов
            int id = 0;

            foreach (var node in sorted_nodes)
            {
                if (ids[node] == 0)
                {
                    SCC(node, id, ref stack, ref scc, ref ids, ref lowLinks);
                }
            }

            // устанавливаем пропускные способности ребер связанных компонентов
            var contracted_admissible_edges = new List <FlowEdge>();

            foreach (var edge in admissible_edges)
            {
                string res = "00";
                foreach (var contracted in scc.Where((list) => list.Count() > 1))
                {
                    res = $"{(contracted.Contains(edge.From) ? 1 : 0)}{(contracted.Contains(edge.To) ? 1 : 0)}";
                    switch (res)
                    {
                    //case "00": contracted_admissible_edges.Add(edge); break;
                    case "01":
                        var e   = new FlowEdge(edge.From, contracted.First(), edge.ResidualCapacityTo(edge.To));
                        var idx = contracted_admissible_edges.IndexOf(e);
                        if (idx == -1)
                        {
                            contracted_admissible_edges.Add(e);
                        }
                        else
                        {
                            contracted_admissible_edges[idx].Capacity += edge.ResidualCapacityTo(edge.To);
                        }
                        break;

                    case "10":
                        e   = new FlowEdge(contracted.First(), edge.To, edge.ResidualCapacityTo(edge.To));
                        idx = contracted_admissible_edges.IndexOf(e);
                        if (idx == -1)
                        {
                            contracted_admissible_edges.Add(e);
                        }
                        else
                        {
                            contracted_admissible_edges[idx].Capacity += edge.ResidualCapacityTo(edge.To);
                        }
                        break;
                    }
                }
                if (String.Equals(res, "00"))
                {
                    contracted_admissible_edges.Add(new FlowEdge(edge));
                }
            }

            // создаем граф
            var contracted_graph = new FlowNetwork(contracted_admissible_edges);

            contracted_graph.Source = graph.Source;
            contracted_graph.Target = graph.Target;
            return(contracted_graph);
        }
Exemplo n.º 28
0
    void CriarNodos()
    {
        List <string> arquivoLido  = new List <string>(LerAqruivo().Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
        List <int>    numerosLidos = new List <int>();

        for (int i = 0; i < arquivoLido.Count; i++)
        {
            numerosLidos.Add(Int32.Parse(arquivoLido[i]));
        }



        for (int i = 0; i < numerosLidos.Count; i = i + 3)
        {
            //print(numerosLidos[i]);
            bool       novo;
            GameObject nodo;
            if (GameObject.Find("Nodo " + numerosLidos[i].ToString()) == null)
            {
                nodo = Instantiate(nodoPrefab, transform.position, Quaternion.identity, transform);
                novo = true;
            }
            else
            {
                nodo = GameObject.Find("Nodo " + numerosLidos[i].ToString());
                novo = false;
            }

            Nodo nodoScript = nodo.GetComponent <Nodo>();

            nodoScript.numero          = numerosLidos[i];
            nodoScript.gameObject.name = "Nodo " + numerosLidos[i].ToString();


            Conexao conexao = Instantiate(conexaoPrefab);
            conexao.transform.SetParent(nodo.transform);
            conexao.origem  = numerosLidos[i];
            conexao.destino = numerosLidos[i + 1];
            conexao.custo   = numerosLidos[i + 2];

            nodoScript.conexoes.Add(conexao);


            if (novo)
            {
                nodos.Add(nodoScript);
            }
        }

        print("numero de nodos na lista: " + nodos.Count);
        int numeroDeConexoes = 0;

        foreach (Nodo nodo in nodos)
        {
            foreach (Conexao conexao in nodo.conexoes)
            {
                numeroDeConexoes++;
            }
        }
        print(numeroDeConexoes);
        FlowNetwork flowNetwork = new FlowNetwork(numeroDeConexoes);

        foreach (Nodo nodo in nodos)
        {
            foreach (Conexao conexao in nodo.conexoes)
            {
                flowNetwork.AddEdge(new FlowEdge(nodo.numero, conexao.destino, conexao.custo));
            }
        }

        FordFulkerson fordFulkerson = new FordFulkerson(flowNetwork, 1, 99);

        print(fordFulkerson.Value);
    }
Exemplo n.º 29
0
 public void EdgeFlowChanged(BaseMaxFlowAlgorithm algorithm, FlowNetwork network, FlowEdge edge)
 {
     AddAnimation(new Animation(edge, AnimationType.EdgeFlowChanged));
 }