Beispiel #1
0
        public static void Main(string[] args)
        {
            //TextWriter textWriter = new StreamWriter(@System.Environment.GetEnvironmentVariable("OUTPUT_PATH"), true);

            int n = Convert.ToInt32(Console.ReadLine().Trim());

            List <int> data = Console.ReadLine().TrimEnd().Split(' ').ToList().Select(dataTemp => Convert.ToInt32(dataTemp)).ToList();

            List <List <int> > edges = new List <List <int> >();

            var GraphInst = new Graph(n);

            for (int i = 0; i < n - 1; i++)
            {
                var edgeData = Array.ConvertAll(Console.ReadLine().Split(' '), x => Convert.ToInt32(x));
                var newEdge  = new WeightedEdge
                {
                    EndVertex = edgeData[1] - 1,
                    weight    = data[edgeData[1] - 1]
                };
                GraphInst.AddEdge(edgeData[0] - 1, newEdge);
                //edges.Add(Console.ReadLine().TrimEnd().Split(' ').ToList().Select(edgesTemp => Convert.ToInt32(edgesTemp)).ToList());
            }
            GraphInst.addData(data);

            long result = GraphInst.cutTheTree();

            Console.WriteLine(result);
            //textWriter.WriteLine(result);

            //textWriter.Flush();
            //textWriter.Close();
        }
Beispiel #2
0
        public void MaxValueEdgeIsLessThanPositiveInfinityEdge()
        {
            var edge1 = new WeightedEdge <int>(0, 1, double.MaxValue);
            var edge2 = new WeightedEdge <int>(0, 1, double.PositiveInfinity);

            Assert.AreEqual(-1, edge1.CompareTo(edge2));
        }
            public Vertex AddNeighbor(TWeight weight, TValue to)
            {
                var vertex = new Vertex(_graph, to);
                var edge   = new WeightedEdge <TWeight>(this, vertex, weight);

                return(AddNeighbor(edge, vertex) as Vertex);
            }
Beispiel #4
0
        private IBidirectionalGraph <Node, IEdge <Node> > CreateGraph(Node root)
        {
            var graph = new BidirectionalGraph <Node, IEdge <Node> >();
            var nodes = new Queue <Node>();

            graph.AddVertex(root);
            nodes.Enqueue(root);

            while (nodes.Count > 0)
            {
                var node = nodes.Dequeue();

                if (node.left != null)
                {
                    var edge = new WeightedEdge <Node>(node, node.left, 0);

                    graph.AddVertex(node.left);
                    graph.AddEdge(edge);
                    nodes.Enqueue(node.left);
                }

                if (node.right != null)
                {
                    var edge = new WeightedEdge <Node>(node, node.right, 1);

                    graph.AddVertex(node.right);
                    graph.AddEdge(edge);
                    nodes.Enqueue(node.right);
                }
            }

            return(graph);
        }
Beispiel #5
0
        public void EqualsTest()
        {
            WeightedEdge <int> edge1 = new WeightedEdge <int>(1, 2);
            object             edge2 = new WeightedEdge <int>(1, 2);

            Assert.IsTrue(edge1.Equals(edge2));
        }
        /// <summary>
        /// Connects two vertices together with a weight, in the direction: first->second.
        /// </summary>
        public bool AddEdge(T source, T destination, long weight)
        {
            // Check existence of nodes, the validity of the weight value, and the non-existence of edge
            if (weight == EMPTY_EDGE_VALUE)
            {
                return(false);
            }
            else if (!HasVertex(source) || !HasVertex(destination))
            {
                return(false);
            }
            else if (_doesEdgeExist(source, destination))
            {
                return(false);
            }

            // Add edge from source to destination
            var edge = new WeightedEdge <T>(source, destination, weight);

            _adjacencyList[source].Append(edge);

            // Increment edges count
            ++_edgesCount;

            return(true);
        }
Beispiel #7
0
        public WeightedGraph(Dictionary <Vector2Int, int> locations)
        {
            mVertices = new List <WeightedNode>();

            foreach (var loc in locations)
            {
                var vertex = loc.Key;
                mVertices.Add(new WeightedNode(vertex));
            }

            foreach (var loc in locations)
            {
                var vertex = loc.Key;
                foreach (var neighbor in vertex.GetNeighbors())
                {
                    if (locations.Keys.Contains(neighbor))
                    {
                        WeightedNode mFirst  = mVertices.SingleOrDefault(v => v.mVertex == vertex);
                        WeightedNode mSecond = mVertices.SingleOrDefault(v => v.mVertex == neighbor);

                        WeightedEdge edge = new WeightedEdge(mFirst, mSecond, locations[vertex]);
                        mFirst.mNeighbors.Add(edge);
                        mSecond.mNeighbors.Add(edge);
                    }
                }
            }
        }
Beispiel #8
0
        private static HashSet <T> MarkEdgeAsProcessed(WeightedEdge <T> edge, HashSet <T> processedVertices)
        {
            processedVertices.Add(edge.Source);
            processedVertices.Add(edge.Destination);

            return(processedVertices);
        }
Beispiel #9
0
        private static bool HasCycle(Dictionary <T, HashSet <T> > edgeLookup, WeightedEdge <T> candidateEdge)
        {
            foreach (var sourceVertex in edgeLookup.Keys)
            {
                var queue             = new Queue <T>(new[] { sourceVertex });
                var processedVertices = new HashSet <T>(edgeLookup.Comparer);

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

                    if (processedVertices.Contains(currentVertex))
                    {
                        return(true);
                    }

                    processedVertices.Add(currentVertex);

                    foreach (var neighbor in edgeLookup[currentVertex])
                    {
                        queue.Enqueue(neighbor);
                    }

                    if (edgeLookup.Comparer.Equals(currentVertex, candidateEdge.Source))
                    {
                        queue.Enqueue(candidateEdge.Destination);
                    }
                }
            }

            return(false);
        }
Beispiel #10
0
        void AddEdge(T from, T to, long weight)
        {
            Vertex       source = GetVertex(from);
            Vertex       target = GetVertex(to);
            WeightedEdge edge   = new WeightedEdge(source, target, weight);

            _edges.Add(edge);
        }
Beispiel #11
0
        public override void AddEdge(Vertex <T> v1, Vertex <T> v2, int cost)
        {
            var edge = new WeightedEdge <T> {
                From = v1, To = v2, Cost = cost
            };

            v1.Neighbors.Add(edge);

            Edges.Add(edge);
        }
Beispiel #12
0
        public void addEdge(int firstVertex, int secondVertex, double weight)
        {
            WeightedNode first  = (WeightedNode)mVerticies[firstVertex];
            WeightedNode second = (WeightedNode)mVerticies [secondVertex];

            WeightedEdge edge = new WeightedEdge(first, second, weight);

            first.getNeighbors().Add(edge);
            second.getNeighbors().Add(edge);
        }
        public Optional <IEnumerable <WeightedEdge <T> > > FindSpanningTreeEdges(IGraph <T> graph)
        {
            if (graph == null)
            {
                throw new ArgumentNullException(nameof(graph));
            }

            if (graph.Count == 0)
            {
                return(Optional <IEnumerable <WeightedEdge <T> > > .None());
            }

            var source            = _sourceNodeProvider(graph);
            var distances         = InitializeDistanceTable(graph, source);
            var verticesToProcess = new MinBinaryHeap <DistanceInfo <T> >(DistanceInfo <T> .DistanceComparer);
            var processedVertices = new HashSet <T>(graph.Comparer);
            var spanningTree      = new HashSet <WeightedEdge <T> >(WeightedEdge <T> .NonDirectionalComparer(graph.Comparer));

            verticesToProcess.Push(DistanceInfo <T> .Zero(source));

            while (verticesToProcess.Count > 0)
            {
                var currentVertex  = verticesToProcess.Pop().Single().PreviousVertex;
                var sourceDistance = distances[currentVertex];

                processedVertices.Add(currentVertex);

                if (graph.Comparer.Equals(source, currentVertex) == false)
                {
                    var edge = new WeightedEdge <T>(sourceDistance.PreviousVertex, currentVertex, sourceDistance.Distance);
                    if (spanningTree.Contains(edge) == false)
                    {
                        spanningTree.Add(edge);
                    }
                }

                foreach (var destinationVertex in graph.GetAdjacentVertices(currentVertex))
                {
                    if (processedVertices.Contains(destinationVertex))
                    {
                        continue;
                    }

                    var step = StepMetadata <T> .ForSpanningTree(currentVertex, destinationVertex, distances);

                    if (step.FoundShorterDistance())
                    {
                        distances[destinationVertex] = step.ToSource();
                        verticesToProcess.Push(step.ToDestination());
                    }
                }
            }

            return(spanningTree);
        }
        public virtual int Solve(Vertex start, Vertex end)
        {
            if (start == null || end == null)
            {
                throw new ApplicationException("DjikstraShortestPath.Solve - one of the vertices is null");
            }

            // Mark the origin as visited. We don't have to consider that node anymore.
            this.Visited[this.Graph.GetVertexIndex(start)] = true;

            // Starting at the origin, traverse edges until we get to the destination
            for (Vertex vertex = start; vertex != end && vertex != null;)
            {
                // These three variables hold the information about the min-cost edge as we check all edges from the current node
                Vertex             minVertex = null;
                WeightedEdge <int> minEdge   = null;
                int min = Int32.MaxValue;

                // Find all vertices that are connected to the current node. Go through all of the edges, and don't consider vertices that have been visited already.
                var edges = this.Graph.GetEdges(vertex);
                foreach (var edge in edges)
                {
                    // Don't consider nodes that have been visited already
                    Vertex otherVertex = edge.Dest == vertex ? edge.Source : edge.Dest;
                    if (this.Visited[this.Graph.GetVertexIndex(otherVertex)])
                    {
                        continue;
                    }

                    // Disregard this edge if it is not the minimum-cost edge under consideration
                    if (edge.Cost >= min)
                    {
                        continue;
                    }

                    // We found a new edge with a minimum cost
                    minVertex = otherVertex;
                    minEdge   = edge;
                    min       = edge.Cost;
                }

                if (minEdge == null)
                {
                    break;
                }

                // Add the lowest-cost edge to the path, and make the 'current' vertex the endpoint of the min edge
                this.Path.AddEdge(minEdge);
                vertex = minVertex;
                this.Visited[this.Graph.GetVertexIndex(vertex)] = true;
            }

            return(this.Path.TotalCost);
        }
Beispiel #15
0
        /// <summary>
        /// This is a special version of the Shortest Path for the ThoughtWorks problem where we need to travel from B to B.
        /// We cannot mark B as "visited" to start with, cause this fucntion will return right away with a zero cost.
        /// </summary>
        public override int Solve(Vertex start, Vertex end)
        {
            if (start == null || end == null)
            {
                throw new ApplicationException("DjikstraShortestPath.Solve - one of the vertices is null");
            }

            //this.m_visited[this.m_graph.GetVertexIndex(start)] = true;

            for (Vertex vertex = start; vertex != null;)
            {
                Vertex             minVertex = null;
                WeightedEdge <int> minEdge   = null;
                int min = Int32.MaxValue;

                var edges = this.Graph.GetEdges(vertex);
                foreach (var edge in edges)
                {
                    // Don't consider nodes that have been visited already
                    Vertex otherVertex = edge.Dest == vertex ? edge.Source : edge.Dest;
                    if (this.Visited[this.Graph.GetVertexIndex(otherVertex)])
                    {
                        continue;
                    }

                    // Disregard this edge if it is not the minimum-cost edge under consideration
                    if (edge.Cost >= min)
                    {
                        continue;
                    }

                    // We found a new edge with a minimum cost
                    minVertex = otherVertex;
                    minEdge   = edge;
                    min       = edge.Cost;
                }

                if (minEdge == null)
                {
                    break;
                }

                this.Path.AddEdge(minEdge);
                vertex = minVertex;
                this.Visited[this.Graph.GetVertexIndex(vertex)] = true;

                if (vertex == end)
                {
                    break;
                }
            }

            return(this.Path.TotalCost);
        }
Beispiel #16
0
        public void AddWeightedEdge(Graph graph, WeightedEdge weightedEdge)
        {
            Assert.AssertAboutGraph(graph);
            Assert.AssertAboutWeightedEdge(weightedEdge);

            if (!graph.Vertices.Any(x => x.Number == weightedEdge.VertexOne.Number || x.Number == weightedEdge.VertexTwo.Number))
            {
                throw new ArgumentException("Некорректные номера для вершин", nameof(weightedEdge));
            }

            graph.Edges.Add(weightedEdge);
        }
        public static WeightedGraph <ReadingTag> createWeightedGraph(int projectId, bool includeReadingTags, bool includeHighlightTags)
        {
            string str = DatabaseInterface.databaseConnectionStr;

            using (SqlConnection con = new SqlConnection(str))
            {
                WeightedGraph <ReadingTag>        graph;
                List <Vertex <ReadingTag> >       vertices = new List <Vertex <ReadingTag> >();
                List <WeightedEdge <ReadingTag> > edges    = new List <WeightedEdge <ReadingTag> >();
                DatabaseInterface.getReadingLinks(con, false);
                List <ReadingTag>   tags  = DatabaseInterface.getReadingTags(null, con, false);
                List <HighlightTag> hTags = DatabaseInterface.getHighlightTags(null, con, false);
                int            numTags    = tags.Count();
                List <TagLink> tagLinks   = DatabaseInterface.getReadingLinks(con, false);
                //List<List<List<int>>> table = new List<List<List<int>>>();
                List <int>[,] table = new List <int> [numTags, numTags];

                foreach (TagLink l in tagLinks)
                {
                    if (table[l.t1, l.t2] == null)
                    {
                        table[l.t1, l.t2] = new List <int>();
                    }
                    table[l.t1, l.t2].Add(l.rId);
                }

                Dictionary <string, Vertex <ReadingTag> > dick = new Dictionary <string, Vertex <ReadingTag> >();

                foreach (ReadingTag t in tags)
                {
                    Vertex <ReadingTag> v = new Vertex <ReadingTag>(t);
                    dick.Add(t.tagId.ToString(), v);
                    vertices.Add(v);
                }

                for (int i = 0; i < tags.Count(); i++)
                {
                    for (int j = 0; j < tags.Count(); j++)
                    {
                        if (table[i, j] != null && table[i, j].Count() > 0)
                        {
                            WeightedEdge <ReadingTag> edge = new WeightedEdge <ReadingTag>(dick[i.ToString()], dick[j.ToString()], table[i, j].Count());
                            edge.ReadingIds = table[i, j];
                            edges.Add(edge);
                        }
                    }
                }
                graph = new WeightedGraph <ReadingTag>(vertices, edges);
                return(graph);
            }
        }
Beispiel #18
0
        //        private void InitializeSingleSource(int src)
//        {
//            src--;
//            int size = graph.Size;
////            graph.MinWeights = new Dictionary<int, int>();
//            for (int i = 0; i < size; i++)
//            {
//                graph.Preds[i] = -1;
//                graph.Marks[i] = posInf;
////                graph.MinWeights.Add(i, posInf);
//            }
//            graph.Marks[src] = 0; //for source vtx predecessor is 0
//        }

        /// <summary>
        /// Optimizes distances from src to edge.Dest through edge.Src
        /// </summary>
        /// <param name="heap">Heap that stores non-proceeded vertices</param>
        /// <param name="edge">Adjacent edge to temp vertex</param>
        private void Relaxation(MinHeap heap, WeightedEdge edge)
        {
            //consider (u,v) edge
            int src      = edge.Src;
            int dest     = edge.Dest;
            int uvWeight = edge.Weight;

            if (graph.Marks[dest] > graph.Marks[src] + uvWeight)
            {
                graph.Marks[dest] = graph.Marks[src] + uvWeight;
                graph.Preds[dest] = src;
                heap.DecreaseKey(dest, graph.Marks[dest]);
            }
        }
Beispiel #19
0
        public override void AddEdge(Vertex <T> v1, Vertex <T> v2, int cost)
        {
            var fwd = new WeightedEdge <T> {
                From = v1, To = v2, Cost = cost
            };
            var back = new WeightedEdge <T> {
                From = v2, To = v1, Cost = cost
            };

            v1.Neighbors.Add(fwd);
            v2.Neighbors.Add(back);

            Edges.Add(fwd);
            Edges.Add(back);
        }
Beispiel #20
0
        public void AddShortcut(Shortcut shortcut, int weight = 1)
        {
            if (Shortcuts.ContainsKey(shortcut))
            {
                return;
            }

            var p1 = GetNode(shortcut.Start);
            var p2 = GetNode(shortcut.End);

            var newEdge = new WeightedEdge(p1, p2, weight);

            Shortcuts[shortcut] = newEdge;
            AddEdge(newEdge);
        }
Beispiel #21
0
        public void AdjacencyTest()
        {
            WeightedEdge we1 = new WeightedEdge(6, 7);
            WeightedEdge we2 = new WeightedEdge(4, 6);

            bool?result = graph.AreAdjacent(we1, we2);

            if (result.HasValue)
            {
                Console.WriteLine("v1 and v2 are adjacent");
            }
            else
            {
                Console.WriteLine("v1 and v2 aren't adjacent");
            }
        }
Beispiel #22
0
        public SCG.ICollection <WeightedEdge <T> > GetShortestPath(T to)
        {
            LinkedList <WeightedEdge <T> > stack = new LinkedList <WeightedEdge <T> >();

            if (_parents.Contains(to))
            {
                WeightedEdge <T> edge = _parents[to];
                while (edge != WeightedEdge <T> .None)
                {
                    stack.InsertFirst(edge);
                    edge = _parents[edge.From];
                }
            }

            return(stack);
        }
Beispiel #23
0
        public void RemoveWeightedEdge(Graph graph, WeightedEdge weightedEdge)
        {
            Assert.AssertAboutGraph(graph);
            Assert.AssertAboutWeightedEdge(weightedEdge);

            var edgeForRemove = graph.Edges.FirstOrDefault(x =>
                                                           (x.VertexOne.Number == weightedEdge.VertexOne.Number && x.VertexTwo.Number == weightedEdge.VertexTwo.Number) ||
                                                           (x.VertexOne.Number == weightedEdge.VertexTwo.Number && x.VertexTwo.Number == weightedEdge.VertexOne.Number));

            if (edgeForRemove == null)
            {
                throw new ArgumentException("Граф не содержит данное ребро");
            }

            graph.Edges.Remove(edgeForRemove);
        }
Beispiel #24
0
        public static void AssertAboutWeightedEdge(WeightedEdge weightedEdge)
        {
            if (weightedEdge == null)
            {
                throw new ArgumentNullException(nameof(weightedEdge));
            }

            if (weightedEdge.VertexOne == null)
            {
                throw new ArgumentNullException(nameof(weightedEdge.VertexOne));
            }

            if (weightedEdge.VertexTwo == null)
            {
                throw new ArgumentNullException(nameof(weightedEdge.VertexTwo));
            }
        }
        /// <summary>
        /// Helper function. Returns edge object from source to destination, if exists; otherwise, null.
        /// </summary>
        protected virtual WeightedEdge <T> _tryGetEdge(T source, T destination)
        {
            WeightedEdge <T> edge = null;

            // Predicate
            var sourceToDestinationPredicate = new Predicate <WeightedEdge <T> >((item) => item.Source.IsEqualTo <T>(source) && item.Destination.IsEqualTo <T>(destination));

            // Try to find a match
            if (_adjacencyList.ContainsKey(source))
            {
                _adjacencyList[source].TryFindFirst(sourceToDestinationPredicate, out edge);
            }

            // Return!
            // Might return a null object.
            return(edge);
        }
Beispiel #26
0
        private WeightedEdge GetMinOrDefaultEdgePointingToVisitedSet(IEnumerable <WeightedEdge> edges)
        {
            WeightedEdge minEdge = null;
            int          min     = int.MaxValue;

            foreach (var edge in edges)
            {
                if (!_visited.Contains(edge.Destination) || edge.Weight >= min)
                {
                    continue;
                }

                min     = edge.Weight;
                minEdge = edge;
            }

            return(minEdge);
        }
Beispiel #27
0
        /// <summary>
        /// Get bidirectional graph from input graph
        /// </summary>
        /// <param name="graph">GraphMapData</param>
        /// <returns>BidirectionalGraph</returns>
        public static BidirectionalGraph <string, WeightedEdge <string> > GetBidirectionalGraph(GraphMapData graph)
        {
            ICollection <NodeMapData> nodes = graph.GetNodes();
            BidirectionalGraph <string, WeightedEdge <string> > bidirectionalGraph = new BidirectionalGraph <string, WeightedEdge <string> >(true, nodes.Count);

            foreach (NodeMapData node in nodes)
            {
                bidirectionalGraph.AddVertex(node.Id);
            }

            foreach (EdgeMapData edge in graph.GetEdges())
            {
                WeightedEdge <string> weightedEdge = new WeightedEdge <string>(edge.Source, edge.Target, edge.Weight);
                bidirectionalGraph.AddEdge(weightedEdge);
            }

            return(bidirectionalGraph);
        }
Beispiel #28
0
            public void AddEdge(long source, WeightedEdge data)
            {
                if (!Adj[source].Contains(data))
                {
                    Adj[source].Add(data);
                }

                var reveresedEdge = new WeightedEdge
                {
                    weight    = data.weight,
                    EndVertex = source
                };

                if (!Adj[data.EndVertex].Contains(reveresedEdge))
                {
                    Adj[data.EndVertex].Add(reveresedEdge);
                }
            }
        /// <summary>
        /// Get all incoming directed weighted edges to a vertex.
        /// </summary>
        public virtual IEnumerable <WeightedEdge <T> > IncomingEdges(T vertex)
        {
            if (!HasVertex(vertex))
            {
                throw new KeyNotFoundException("Vertex doesn't belong to graph.");
            }

            var predicate = new Predicate <WeightedEdge <T> >((edge) => edge.Destination.IsEqualTo(vertex));

            foreach (var adjacent in _adjacencyList.Keys)
            {
                WeightedEdge <T> incomingEdge = null;

                if (_adjacencyList[adjacent].TryFindFirst(predicate, out incomingEdge))
                {
                    yield return(incomingEdge);
                }
            }//end-foreach
        }
Beispiel #30
0
 public GraphLayout()
 {
     if (DesignerProperties.GetIsInDesignMode(this))
     {
         var g        = new BidirectionalWeightedGraph <object, WeightedEdge <object> >();
         var vertices = new object[] { "S", "A", "M", "P", "L", "E" };
         var edges    = new WeightedEdge <object>[] {
             new WeightedEdge <object>(vertices[0], vertices[1]),
             new WeightedEdge <object>(vertices[1], vertices[2]),
             new WeightedEdge <object>(vertices[1], vertices[3]),
             new WeightedEdge <object>(vertices[3], vertices[4]),
             new WeightedEdge <object>(vertices[0], vertices[4]),
             new WeightedEdge <object>(vertices[4], vertices[5])
         };
         g.AddVerticesAndEdgeRange(edges);
         OverlapRemovalAlgorithmType = "FSA";
         LayoutAlgorithmType         = "FR";
         Graph = g;
     }
 }
Beispiel #31
0
        /// <summary>
        /// Get bidirectional graph from input graph
        /// </summary>
        /// <param name="graph">GraphMapData</param>
        /// <returns>BidirectionalGraph</returns>
        public static BidirectionalGraph<string, WeightedEdge<string>> GetBidirectionalGraph(GraphMapData graph)
        {
            ICollection<NodeMapData> nodes = graph.GetNodes();
            BidirectionalGraph<string, WeightedEdge<string>> bidirectionalGraph = new BidirectionalGraph<string, WeightedEdge<string>>(true, nodes.Count);

            foreach (NodeMapData node in nodes)
            {
                bidirectionalGraph.AddVertex(node.Id);
            }

            foreach (EdgeMapData edge in graph.GetEdges())
            {
                WeightedEdge<string> weightedEdge = new WeightedEdge<string>(edge.Source, edge.Target, edge.Weight);
                bidirectionalGraph.AddEdge(weightedEdge);
            }

            return bidirectionalGraph;
        }