示例#1
0
        public static PathStats ShortestPath(DirectedGraph g, int s)
        {
            #region Initialization
            var stats = new PathStats(g.V);
            for (var i = 0; i < stats.Dist.Length; i++)
            {
                stats.Dist[i] = int.MaxValue;
                stats.Prev[i] = -1;
            }
            stats.Dist[s] = 0;
            #endregion

            var dfsStats = Dfs.DepthFirstSearch(g);
            var linearization = dfsStats.Linearization;
            Debug.WriteLine(dfsStats);
            foreach (var u in linearization)
            {
                foreach (var v in g.Adjacent(u))
                {
                    if (stats.Dist[v.V2] > stats.Dist[v.V1] + v.Weight)
                    {
                        stats.Dist[v.V2] = stats.Dist[v.V1] + v.Weight;
                        stats.Prev[v.V2] = u;
                    }
                }
            }

            return stats;
        }
        /// <summary>
        /// Give a sequence of number, find the longest increasing subsequence
        /// </summary>
        /// <param name="numbers"></param>
        /// <returns></returns>
        public static string GetLongest(int[] numbers)
        {
            //var g = new DirectedGraph(numbers.Length);
            var g = new DirectedGraph(10);
            for (var i = 0; i < numbers.Length; i++)
            {
                for (var j = i + 1; j < numbers.Length; j++)
                {
                    if (numbers[i] < numbers[j])
                    {
                        g.AddEdge(numbers[i], numbers[j], 1);
                    }
                }
            }

            g.ReverseGraph();

            Debug.WriteLine(Dfs.StrongConnectedComponentAlgorithm(g));

            var v = Dfs.GetSource(g);

            g.ReverseGraph();//reverse back
            var stats = Dijkstra.LongestPath(g, v);
            //Debug.WriteLine(stats);
            return string.Empty;
        }
示例#3
0
        public static DfsStats StrongConnectedComponentAlgorithm(DirectedGraph g)
        {
            g.ReverseGraph();//reverse G
            var linearization = GetLinearization(g);

            var ds = new DfsStats(g.V) { Clock = 1, ComponentCount = 0 };

            g.ReverseGraph();//reverse G back
            foreach (var v in linearization)
            {
                if (!ds.Visited[v])
                {
                    ds.ComponentCount++;
                    Explore(g, v, ds);
                }
            }

            return ds;
        }
示例#4
0
 /// <summary>
 /// Get predecessor of a DAG
 /// </summary>
 /// <param name="g">Graph g to be searched</param>
 /// <returns>Predecessor of a node of a DAG</returns>
 public static int GetSource(DirectedGraph g)
 {
     var ds = StrongConnectedComponentAlgorithm(g);
     return ds.Linearization.ToArray()[0];
 }