コード例 #1
0
        public void NoExpertsTest()
        {
            var experts = new List <Expert>()
            {
            };
            var projects = new List <Project>()
            {
                new Project(0, new List <int> {
                    1, 0, 1
                }),
                new Project(1, new List <int> {
                    1, 0, 1
                }),
            };

            var   solver    = new ProblemSolver(experts, projects);
            Graph graphFlow = solver.Solve();

            if (graphFlow == null)
            {
                return;
            }

            GraphExport ge = new GraphExport();

            ge.Export(graphFlow, null, "Graph");
        }
コード例 #2
0
        public void CalculateMaxFlow_BasicTest()
        {
            //arrange
            var g = new AdjacencyMatrixGraph(true, 11);

            g.AddEdge(0, 1, 2);
            g.AddEdge(0, 2);

            g.AddEdge(2, 6);
            g.AddEdge(1, 4);
            g.AddEdge(1, 3);

            g.AddEdge(6, 9);
            g.AddEdge(4, 8);
            g.AddEdge(3, 7);
            g.AddEdge(2, 5);
            g.AddEdge(5, 8);


            g.AddEdge(8, 10);
            g.AddEdge(9, 10);
            g.AddEdge(8, 10);
            g.AddEdge(7, 10);

            //act
            var test = new BestAllocationFinder(g);
            //act
            var res = test.CalculateMaxFlow();

            //assert
            //prev.ShouldAllBeEquivalentTo(new int[] { -1, 0, 1, 0 });
            var ge = new GraphExport();

            ge.Export(res);
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: DarkAlek/Tajo
        private static void VisualizeResultGraphs(GraphExport ge, Graph g1, Graph g2, Dictionary <int, int> mapping)
        {
            String[] verticesDescriptions1 = new String[g1.VerticesCount];
            String[] verticesDescriptions2 = new String[g2.VerticesCount];

            for (int it = 0; it < verticesDescriptions1.Length; ++it)
            {
                verticesDescriptions1[it] = it.ToString();
            }

            for (int it = 0; it < verticesDescriptions2.Length; ++it)
            {
                verticesDescriptions2[it] = it.ToString();
            }

            int i = 0;

            foreach (var el in mapping)
            {
                verticesDescriptions1[el.Key]   = el.Key.ToString() + "(" + i.ToString() + ")";
                verticesDescriptions2[el.Value] = el.Value.ToString() + "(" + i.ToString() + ")";
                i++;
            }

            try
            {
                ge.Export(g1, null, verticesDescriptions1);
                ge.Export(g2, null, verticesDescriptions2);
            }
            catch
            {
                Console.WriteLine("GraphViz isn't installed. Graphs will be not visualized.");
            }
        }
コード例 #4
0
    public static void Main()
    {
        var ge = new GraphExport();

        int[] clique, map;
        bool  izo;
        int   n, ec, ec0, ec1;

        PrepareTests();

        Console.WriteLine();
        Console.WriteLine("Clique Tests");
        for (int i = 0; i < cliq_test.Length; ++i)
        {
            try
            {
                ec = cliq_test[i].EdgesCount;
                n  = cliq_test[i].CliqueNumber(out clique);
                Console.WriteLine("Test {0}:  {1} ", i + 1, CliqueTest(cliq_test[i], n, clique) && n == cliq_res[i] && ec == cliq_test[i].EdgesCount);
                if (i > 0)
                {
                    continue;
                }
                //ge.Export(cliq_test[i], null, "clique");
                Console.Write("  [");
                foreach (var v in clique)
                {
                    Console.Write(" {0} ", v);
                }
                Console.WriteLine("]");
            }
            catch (Exception e)
            {
                Console.WriteLine("Test {0}:  {1} ", i + 1, e.Message);
            }
        }

        Console.WriteLine();
        Console.WriteLine("Izomorpism Tests");
        for (int i = 0; i < izo_test.GetLength(0); ++i)
        {
            try
            {
                ec0 = izo_test[i, 0].EdgesCount;
                ec1 = izo_test[i, 1].EdgesCount;
                izo = izo_test[i, 0].IsIzomorpchic(izo_test[i, 1], out map);            // The result is correct (true, false, true, false), only the checking function is wrong
                int[] libraryIsomorphism = izo_test[i, 0].Isomorpchism(izo_test[i, 1]); // This fails every time, I don't know why
                Console.WriteLine("Test {0}:  {1} ", i + 1, (izo ? izo_res[i] && IzomorphismTest(izo_test[i, 0], izo_test[i, 1], map) == izo_res[i] : !izo_res[i]) &&
                                  ec0 == izo_test[i, 0].EdgesCount && ec1 == izo_test[i, 1].EdgesCount);
            }
            catch (Exception e)
            {
                Console.WriteLine("Test {0}:  {1} ", i + 1, e.Message);
            }
        }

        Console.WriteLine();
    }
コード例 #5
0
    public static void Main()
    {
        var ge = new GraphExport();

        int[] clique, map;
        bool  izo;
        int   n, ec, ec0, ec1;

        PrepareTests();

        Console.WriteLine();
        Console.WriteLine("Clique Tests");
        for (int i = 0; i < cliq_test.Length; ++i)
        {
            try
            {
                ec = cliq_test[i].EdgesCount;
                n  = cliq_test[i].CliqueNumber(out clique);
                Console.WriteLine("Test {0}:  {1} ", i + 1, CliqueTest(cliq_test[i], n, clique) && n == cliq_res[i] && ec == cliq_test[i].EdgesCount);
                if (i > 0)
                {
                    continue;
                }
                ge.Export(cliq_test[i], null, "clique");
                Console.Write("  [");
                foreach (var v in clique)
                {
                    Console.Write(" {0} ", v);
                }
                Console.WriteLine("]");
            }
            catch (Exception e)
            {
                Console.WriteLine("Test {0}:  {1} ", i + 1, e.Message);
            }
        }

        Console.WriteLine();
        Console.WriteLine("Izomorpism Tests");
        for (int i = 0; i < izo_test.GetLength(0); ++i)
        {
            try
            {
                ec0 = izo_test[i, 0].EdgesCount;
                ec1 = izo_test[i, 1].EdgesCount;
                izo = izo_test[i, 0].IsIzomorpchic(izo_test[i, 1], out map);
                Console.WriteLine("Test {0}:  {1} ", i + 1, (izo ? izo_res[i] && izo_test[i, 0].IzomorphismTest(izo_test[i, 1], map) == izo_res[i] : !izo_res[i]) &&
                                  ec0 == izo_test[i, 0].EdgesCount && ec1 == izo_test[i, 1].EdgesCount);
            }
            catch (Exception e)
            {
                Console.WriteLine("Test {0}:  {1} ", i + 1, e.Message);
            }
        }

        Console.WriteLine();
    }
コード例 #6
0
        public void ToManyExpertsTest()
        {
            var experts = new List <Expert>()
            {
                new Expert(0, new List <bool> {
                    true, false, false
                }),
                new Expert(1, new List <bool> {
                    false, false, true
                }),
                new Expert(2, new List <bool> {
                    true, false, false
                }),
                new Expert(3, new List <bool> {
                    false, false, true
                }),
                new Expert(4, new List <bool> {
                    false, false, true
                }),
                new Expert(5, new List <bool> {
                    false, false, true
                }),
                new Expert(6, new List <bool> {
                    false, false, true
                }),
            };
            var projects = new List <Project>()
            {
                new Project(0, new List <int> {
                    1, 0, 1
                }),
                new Project(1, new List <int> {
                    1, 0, 1
                }),
            };

            var         solver    = new ProblemSolver(experts, projects);
            Graph       graphFlow = solver.Solve();
            GraphExport ge        = new GraphExport();

            ge.Export(graphFlow, null, "Graph");
        }
コード例 #7
0
        public void CalculateMaxFlow_SimpleTest()
        {
            //arrange
            var g = new AdjacencyMatrixGraph(true, 5);

            g.AddEdge(0, 1);

            g.AddEdge(1, 2);
            g.AddEdge(2, 3);
            g.AddEdge(3, 4);

            //act
            var test = new BestAllocationFinder(g);
            //act
            var res = test.CalculateMaxFlow();

            //assert
            //prev.ShouldAllBeEquivalentTo(new int[] { -1, 0, 1, 0 });
            var ge = new GraphExport();

            ge.Export(res);
        }
コード例 #8
0
        public override void VerifyTestCase(out Result resultCode, out string message, object settings = null)
        {
            if (colors == null)
            {
                message    = $"No solution";
                resultCode = Result.BadResult;
                return;
            }
            if (expected_colors_number != colors_number)
            {
                message    = $"Incorrect numbers of colors: {colors_number}, should be: {expected_colors_number}";
                resultCode = Result.BadResult;
                return;
            }
            //algorytm podany jest w taki, sposob, ze kolorowanie mozliwe jest tylko jedno - sprawdzam czy tablice sa identyczne
            for (int id = 0; id < colors_number; ++id)
            {
                if (expected_colors[id] != colors[id])
                {
                    //mozna zakomentowac - ma ulatwic zrozumienie bledu
                    var ge = new GraphExport();
                    ge.Export(graph, "Expected");

                    message = $"Incorrect coloring";
                    string c1 = "", c2 = "";
                    for (int i = 0; i < graph.VerticesCount; ++i)
                    {
                        c1 += "[ " + i + ": " + colors[i].ToString() + "] ";
                        c2 += "[ " + i + ": " + expected_colors[i].ToString() + "] ";
                    }
                    message += "\nResult: \n" + c1 + "\n" + "Expected: \n" + c2;
                    //wyswietlic kolorowanie
                    resultCode = Result.BadResult;
                    return;
                }
            }
            resultCode = Result.Success;
            message    = "OK";
        }
コード例 #9
0
        public override void VerifyTestCase(out Result resultCode, out string message, object settings = null)
        {
            if (result_graph == null)
            {
                message    = $"No solution";
                resultCode = Result.BadResult;
                return;
            }
            //tu rozwiazanie jest jednoznaczne - sprawdzamy tylko rownosc grafu, izomorfizm niepotrzebny
            if (expected_result_graph.EdgesCount != result_graph.EdgesCount || !expected_result_graph.IsEqual(result_graph))
            {
                //mozna zakomentowac - ma ulatwic zrozumienie bledu
                var ge = new GraphExport();
                ge.Export(expected_result_graph, "Expected");
                ge.Export(result_graph, "Result");

                message    = $"Incorrect result graph";
                resultCode = Result.BadResult;
                return;
            }
            resultCode = Result.Success;
            message    = "OK";
        }
コード例 #10
0
        public void FullTest_SimpleCase1()
        {
            var f = new FileReader("SimpleCase1.txt");

            var epi = f.ReadFile();

            var baf = new BestAllocationFinder(epi);

            var resGraph = baf.CalculateMaxFlow();

            var e = new GraphExport();

            var res = resGraph.GraphToAllocationResult(epi.ProjectCount, epi.SkillCount, epi.ExpertCount);

            res.ExpertToProjects.Should().HaveCount(3);
            res.ExpertToProjects.FirstOrDefault(x => x.ExpertId == 0 && x.ProjectId == 0 && x.SkillId == 0).Should().NotBeNull();
            res.ExpertToProjects.FirstOrDefault(x => x.ExpertId == 1 && x.ProjectId == 0 && x.SkillId == 0).Should().NotBeNull();
            res.ExpertToProjects.FirstOrDefault(x => x.ExpertId == 2 && x.ProjectId == 1 && x.SkillId == 1).Should().NotBeNull();
            res.ExpertToProjects.FirstOrDefault(x => x.ExpertId == 3 && x.ProjectId == 1 && x.SkillId == 1).Should().NotBeNull();
            res.ExpertToProjects.FirstOrDefault(x => x.ExpertId == 4 && x.ProjectId == 1 && x.SkillId == 1).Should().NotBeNull();
            res.ExpertToProjects.FirstOrDefault(x => x.ExpertId == 5 && x.ProjectId == 1 && x.SkillId == 1).Should().NotBeNull();
            res.ExpertToProjects.FirstOrDefault(x => x.ExpertId == 6 && x.ProjectId == 1 && x.SkillId == 1).Should().NotBeNull();
        }
コード例 #11
0
ファイル: Lab05_main.cs プロジェクト: L-Dogg/ASD2
    public static void Main()
    {
        var ge  = new GraphExport();
        var rgg = new RandomGraphGenerator();

        Graph g1 = new AdjacencyMatrixGraph(true, 15);

        g1.AddEdge(0, 2);
        g1.AddEdge(0, 7);
        g1.AddEdge(1, 0);
        g1.AddEdge(2, 1);
        g1.AddEdge(2, 3);
        g1.AddEdge(2, 7);
        g1.AddEdge(3, 5);
        g1.AddEdge(4, 3);
        g1.AddEdge(5, 4);
        g1.AddEdge(5, 6);
        g1.AddEdge(6, 7);
        g1.AddEdge(7, 6);
        g1.AddEdge(7, 8);
        g1.AddEdge(8, 9);
        g1.AddEdge(10, 0);
        g1.AddEdge(12, 13);
        g1.AddEdge(13, 14);
        g1.AddEdge(14, 12);
        //ge.Export(g1,null, "g1");

        int[] scc;
        int   n;

        n = g1.StronglyConnectedComponents(out scc);
        Console.WriteLine("\nLiczba silnie spojnych skladowych: {0} (powinno byc 8)", n);
        for (int c = 0; c < n; ++c)
        {
            Console.WriteLine();
            Console.Write("skladowa {0}:", c);
            for (int v = 0; v < g1.VerticesCount; ++v)
            {
                if (scc[v] == c)
                {
                    Console.Write(" {0}", v);
                }
            }
        }
        Console.WriteLine();

        Graph k1 = g1.Kernel();

        //ge.Export(k1, null, "k1");

        rgg.SetSeed(500);
        Graph g2 = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 0.005);

        n = g2.StronglyConnectedComponents(out scc);
        Console.WriteLine("\nLiczba silnie spojnych skladowych: {0} (powinno byc 17)", n);

        Graph g3 = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 0.1);

        try
        {
            n = g3.StronglyConnectedComponents(out scc);
            Console.WriteLine("\nBlad - powinien byc wyjatek");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine("\n" + e.Message + "  - dobrze");
        }

        Console.WriteLine("\nSciezka maksymalnie powiekszajaca");
        PathsInfo[] d;
        bool        b;
        Graph       m1 = new AdjacencyMatrixGraph(true, 7);

        m1.AddEdge(0, 2, 10);
        m1.AddEdge(2, 3, 4);
        m1.AddEdge(2, 5, 3);
        m1.AddEdge(2, 4, 7);
        m1.AddEdge(3, 1, 2);
        m1.AddEdge(4, 1, 1);
        m1.AddEdge(5, 6, 5);
        m1.AddEdge(6, 1, 4);
        //ge.Export(m1, null, "m1");

        b = m1.MaxFlowPathsLab05(2, out d);
        Console.WriteLine("graf m1");
        for (int v = 0; v < m1.VerticesCount; ++v)
        {
            Console.WriteLine("przepustowosc od 2 do {0} wynosi {1}", v, d[v].Dist ?? 0);
        }

        int[] p = { 55, 33, 65, 73, 0, 73, 84, 76, 45, 78 };
        rgg.SetSeed(200);
        Graph m2 = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 200, 0.02, 1, 99);

        b = m2.MaxFlowPathsLab05(5, out d);
        Console.WriteLine("graf m2");
        for (int v = 10; v < 20; ++v)
        {
            Console.WriteLine("przepustowosc od 5 do do {0} wynosi {1} ({2})", v, d[v].Dist ?? 0, (d[v].Dist ?? 0) == p[v - 10]?"OK":"blad");
        }

        Console.WriteLine("\nTesty Acyklicznosci\n");
        Graph a1, a2, a3, a4, a5;
        bool  b1, b2, b3, b4, b5;

        rgg.SetSeed(101);
        a1 = rgg.TreeGraph(typeof(AdjacencyListsGraph <SimplyAdjacencyList>), 10, 1);
//        ge.Export(a1,"a1");
        b1 = a1.IsUndirectedAcyclic();
        Console.WriteLine("Czy graf a1 jest acykliczny ? : {0} (powinno byc True)", b1);

        rgg.SetSeed(102);
        a2 = rgg.TreeGraph(typeof(AdjacencyListsGraph <SimplyAdjacencyList>), 15, 1);
        a2.DelEdge(1, 7);
        a2.DelEdge(6, 12);
//        ge.Export(a2,"a2");
        b2 = a2.IsUndirectedAcyclic();
        Console.WriteLine("Czy graf a2 jest acykliczny ? : {0} (powinno byc True)", b2);

        rgg.SetSeed(103);
        a3 = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 10, 0.3);
//        ge.Export(a3,"a3");
        b3 = a3.IsUndirectedAcyclic();
        Console.WriteLine("Czy graf a3 jest acykliczny ? : {0} (powinno byc False)", b3);

        rgg.SetSeed(104);
        a4 = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 1000, 0.1);
        try
        {
            b4 = a4.IsUndirectedAcyclic();
            Console.WriteLine("Blad - powinien byc wyjatek");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine(e.Message);
        }
        Console.WriteLine("Czy graf a4 jest acykliczny ? (przed chwila powinien byc wyjatek)");

        rgg.SetSeed(105);
        a5 = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 2000, 0.8);
        b5 = a5.IsUndirectedAcyclic();
        Console.WriteLine("Czy graf a5 jest acykliczny ? : {0} (powinno byc False)", b5);

        Console.WriteLine("KONIEC !!!\n");
    }
コード例 #12
0
ファイル: Lab10.cs プロジェクト: L-Dogg/ASD2
        /// <summary>
        /// Metoda zwraca graf reprezentujący najliczniejsze skojarzenie w grafie dwudzielnym.
        /// Skojarzenie znajdowane jest przy pomocy algorytmu znajdowania maksymalnego przepływu w sieci.
        /// Dla grafu dwudzielnego (nieskierowanego) G = (X,Y,E) tworzymy sieć N:
        /// V(N) = X u Y u {s,t}
        /// E(N) = { (x,y) : x należy do X i y należy do Y i {x,y} należy do E(G) }
        ///        u {(s,x) : x należy do X }
        ///        u {(y,t) : y należy do Y }
        /// c(e) = 1 dla każdego e należącego do E(N)
        ///
        /// Krawędzie realizujące maksymalny przepływ w sieci N (poza krawędziami zawierającymi źródło i ujście)
        /// odpowiadają najliczniejszemu skojarzeniu w G.
        /// </summary>
        /// <param name="g">Graf dwudzielny</param>
        /// <param name="matching">Znalezione skojarzenie -
        /// graf nieskierowany będący kopią g z usuniętymi krawędziami spoza znalezionego skojarzenia</param>
        /// <returns>Liczność znalezionego skojarzenia</returns>
        /// <remarks>
        /// Uwaga 1: metoda nie modyfikuje zadanego grafu
        /// Uwaga 2: jeśli dany graf nie jest dwudzielny, metoda zgłasza wyjątek ArgumentException
        /// </remarks>
        public static int GetMaxMatching(this Graph g, out Graph matching)
        {
            //
            // TODO (2 pkt.)
            //
            int[] vertices;
            if (!g.Lab03IsBipartite(out vertices))
            {
                throw new ArgumentException();
            }

            Graph flowGraph = g.IsolatedVerticesGraph(true, g.VerticesCount + 2);
            int   s         = g.VerticesCount;
            int   t         = g.VerticesCount + 1;

            for (int i = 0; i < g.VerticesCount; i++)
            {
                foreach (var edge in g.OutEdges(i))
                {
                    if (vertices[i] == 1 && vertices[edge.To] == 2)
                    {
                        flowGraph.AddEdge(edge.From, edge.To);
                    }
                }
                if (vertices[i] == 1)
                {
                    flowGraph.AddEdge(s, i);
                }
                else
                {
                    flowGraph.AddEdge(i, t);
                }
            }
            var ge = new GraphExport();
            //ge.Export(g);
            //ge.Export(flowGraph);

            Graph flow;

            flowGraph.FordFulkersonMaxFlow(s, t, out flow);

            //ge.Export(flow);

            //Jeśli po danej krawędzi nie płynie żaden przepływ, to nadal jest ona w wynikowym grafie flow (oczywiście z wagą 0).
            matching = g.IsolatedVerticesGraph(false, g.VerticesCount);
            for (int i = 0; i < g.VerticesCount; i++)                                           // źródło i ujście pomijamy
            {
                foreach (Edge e in flow.OutEdges(i))
                {
                    if (e.To == s || e.To == t || e.Weight == 0)                        // źródło i ujście pomijamy
                    {
                        continue;
                    }
                    else
                    {
                        matching.AddEdge(e.From, e.To);
                    }
                }
            }
            //ge.Export(matching);
            return(matching.EdgesCount);
        }
コード例 #13
0
ファイル: Lab10.cs プロジェクト: barankiewicz/asd2
        public override void VerifyTestCase(out Result resultCode, out string message, object settings)
        {
            int n = G.VerticesCount;

#if LAB
            GraphExport ge = new GraphExport();
            if (circulation != null && ConstrainedFlows.circulationToDisplay.Contains(counter++))
            {
                string[] desc = new string[n];
                for (int v = 0; v < n; ++v)
                {
                    desc[v] = $"{v} ({demandsRef[v]})";
                }
                ge.Export(circulation, null, desc);
            }
#endif
            message = "";
            // sprawdzam, czy nie zmieniono danych wejściowych
            if (demandsRef.Length != demands.Length)
            {
                message    = $"niedozwolona zmiana w tablicy demands (liczba elementów)";
                resultCode = Result.BadResult;
                return;
            }
            for (int v = 0; v < n; ++v)
            {
                if (demands[v] != demandsRef[v])
                {
                    resultCode = Result.BadResult;
                    message    = $"niedowolona zmiana w demands[{v}]";
                    return;
                }
            }
            if (!G.IsEqual(GRef))
            {
                message    = $"niedozwolona zmiana grafu wejściowego";
                resultCode = Result.BadResult;
                return;
            }

            // sprawdzanie, czy jest poprawna odpowiedź tak/nie
            if (!expectedResult && circulation == null)
            {
                message    = $"OK, brak rozwiązania (time:{PerformanceTime,6:#0.000})";
                resultCode = Result.Success;
                return;
            }
            if (expectedResult && circulation == null)
            {
                message    = $"zwrócono brak rozwiąznia, choć rozwiązanie istnieje";
                resultCode = Result.BadResult;
                return;
            }
            if (!expectedResult && circulation != null)
            {
                message = $"zwrócono rozwiązanie, choć rozwiązania nie ma, ";
//                resultCode = Result.BadResult;
//                return;
            }

            // sprawdzam, czy graf z rozwiązaniem ma poprawną postać i czy przepływy są z przedziału [0, capacity]
            if (circulation.VerticesCount != G.VerticesCount)
            {
                message   += $"niewłaściwa liczba wierzchołków w grafie z wynikowym przepływem (jest {circulation.VerticesCount}, powinno być {G.VerticesCount})";
                resultCode = Result.BadResult;
                return;
            }
            if (circulation.EdgesCount != G.EdgesCount)
            {
                message   += $"niewłaściwa liczba krawędzi w grafie z wynikowym przepływem (jest {circulation.EdgesCount}, powinno być {G.EdgesCount})";
                resultCode = Result.BadResult;
                return;
            }

            for (int v = 0; v < n; ++v)
            {
                foreach (var e in circulation.OutEdges(v))
                {
                    double cap = G.GetEdgeWeight(v, e.To);
                    if (cap.IsNaN())
                    {
                        message   += $"krawędź {e} istnieje w rozwiązaniu, a nie istnieje w grafie";
                        resultCode = Result.BadResult;
                        return;
                    }
                    if (e.Weight < 0 || e.Weight > cap)
                    {
                        message   += $"krawędź {e} ma przepływ {e.Weight} przy przepustowości {cap}";
                        resultCode = Result.BadResult;
                        return;
                    }
                }
            }

            // sprawdzam, czy spełnione są żądania
            double[] diffs = new double[n];

            for (int v = 0; v < n; ++v)
            {
                foreach (var e in circulation.OutEdges(v))
                {
                    diffs[v]    -= e.Weight;
                    diffs[e.To] += e.Weight;
                }
            }
            for (int v = 0; v < n; ++v)
            {
                if (diffs[v] != demands[v])
                {
                    message   += $"bilans w wierzchołku {v} wynosi {diffs[v]}, a powinien {demands[v]}";
                    resultCode = Result.BadResult;
                    return;
                }
            }
            message   += $"OK (time:{PerformanceTime,6:#0.000})";
            resultCode = Result.Success;
        }
コード例 #14
0
ファイル: Lab10.cs プロジェクト: barankiewicz/asd2
        public override void VerifyTestCase(out Result resultCode, out string message, object settings)
        {
            int n = G.VerticesCount;

#if LAB
            GraphExport ge = new GraphExport();
            if (flow != null && ConstrainedFlows.constrainedFlowToDisplay.Contains(counter++))
            {
                string[] desc = new string[n];
                for (int v = 0; v < n; ++v)
                {
                    desc[v] = $"{v}";
                }
                ge.Export(flow, null, desc);
            }
#endif
            message = "";
            // sprawdzam, czy nie zmieniono danych wejściowych
            if (!G.IsEqual(GRef))
            {
                message    = $"niedozwolona zmiana grafu G";
                resultCode = Result.BadResult;
                return;
            }
            if (!lower.IsEqual(lowerRef))
            {
                message    = $"niedozwolona zmiana grafu lower";
                resultCode = Result.BadResult;
                return;
            }

            // sprawdzanie, czy jest poprawna odpowiedź tak/nie
            if (!expectedResult && flow == null)
            {
                message    = $"OK, brak rozwiązania (time:{PerformanceTime,6:#0.000})";
                resultCode = Result.Success;
                return;
            }
            if (expectedResult && flow == null)
            {
                message    = $"zwrócono brak rozwiąznia, choć rozwiązanie istnieje";
                resultCode = Result.BadResult;
                return;
            }
            if (!expectedResult && flow != null)
            {
                message = $"zwrócono rozwiązanie, choć rozwiązania nie ma, ";
//                resultCode = Result.BadResult;
//                return;
            }

            // sprawdzam, czy graf z rozwiązaniem ma poprawną postać i czy przepływy są z przedziału [lower, capacity]
            if (flow.VerticesCount != G.VerticesCount)
            {
                message   += $"niewłaściwa liczba wierzchołków w grafie z wynikowym przepływem (jest {flow.VerticesCount}, powinno być {G.VerticesCount})";
                resultCode = Result.BadResult;
                return;
            }
            if (flow.EdgesCount != G.EdgesCount)
            {
                message   += $"niewłaściwa liczba krawędzi w grafie z wynikowym przepływem (jest {flow.EdgesCount}, powinno być {G.EdgesCount})";
                resultCode = Result.BadResult;
                return;
            }

            for (int v = 0; v < n; ++v)
            {
                foreach (var e in flow.OutEdges(v))
                {
                    double cap = G.GetEdgeWeight(v, e.To);
                    double lo  = lower.GetEdgeWeight(v, e.To);
                    if (cap.IsNaN())
                    {
                        message   += $"krawędź {e} istnieje w rozwiązaniu, a nie istnieje w grafie";
                        resultCode = Result.BadResult;
                        return;
                    }
                    if (e.Weight < lo || e.Weight > cap)
                    {
                        message   += $"krawędź {e} ma przepływ {e.Weight}, a powinien być w przedziale [{lo}, {cap}]";
                        resultCode = Result.BadResult;
                        return;
                    }
                }
            }

            // sprawdzam warunek równowagi
            double[] diffs = new double[n];
            for (int v = 0; v < n; ++v)
            {
                foreach (var e in flow.OutEdges(v))
                {
                    diffs[v]    -= e.Weight;
                    diffs[e.To] += e.Weight;
                }
            }
            for (int v = 0; v < n; ++v)
            {
                if (v == source || v == sink)
                {
                    continue;
                }
                if (diffs[v] != 0)
                {
                    message   += $"bilans w wierzchołku {v} wynosi {diffs[v]}, a powinien 0";
                    resultCode = Result.BadResult;
                    return;
                }
            }

            message   += $"OK (time:{PerformanceTime,6:#0.000})";
            resultCode = Result.Success;
        }
コード例 #15
0
        static void Main(string[] args)
        {
            GraphExport          ge  = new GraphExport();
            RandomGraphGenerator rgg = new RandomGraphGenerator();

            Graph[] directedGraphs = new Graph[8];
            directedGraphs[0] = new AdjacencyListsGraph <AVLAdjacencyList>(true, 3)
            {
                new Edge(0, 1), new Edge(1, 2), new Edge(2, 0)
            };
            directedGraphs[1] = new AdjacencyListsGraph <SimpleAdjacencyList>(true, 3)
            {
                new Edge(0, 1), new Edge(1, 2), new Edge(2, 1)
            };
            directedGraphs[2] = new AdjacencyMatrixGraph(true, 4)
            {
                new Edge(0, 1), new Edge(0, 2), new Edge(1, 3), new Edge(2, 3)
            };
            directedGraphs[3] = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 10);
            directedGraphs[4] = new AdjacencyMatrixGraph(true, 10)
            {
                new Edge(0, 1), new Edge(0, 2), new Edge(0, 3), new Edge(2, 4), new Edge(2, 5), new Edge(2, 6),
                new Edge(5, 7), new Edge(5, 8), new Edge(5, 9), new Edge(6, 5), new Edge(7, 8), new Edge(8, 2)
            };
            rgg.SetSeed(111);
            directedGraphs[5] = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.2);
            rgg.SetSeed(222);
            directedGraphs[6] = rgg.DirectedCycle(typeof(AdjacencyListsGraph <SimpleAdjacencyList>), 1000);
            rgg.SetSeed(333);
            directedGraphs[7] = rgg.DAG(typeof(AdjacencyMatrixGraph), 200, 0.2, 1, 1);

            TestSet findCycleDirected = new TestSet();

            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[0], true));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[1], true));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[2], false));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[3], false));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[4], true));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[5], true));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[6], true));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[7], false));

            Graph[] undirectedGraphs = new Graph[6];
            undirectedGraphs[0] = new AdjacencyListsGraph <AVLAdjacencyList>(false, 3)
            {
                new Edge(0, 1), new Edge(1, 2), new Edge(2, 0)
            };
            undirectedGraphs[1] = new AdjacencyListsGraph <SimpleAdjacencyList>(false, 4)
            {
                new Edge(0, 1), new Edge(1, 2), new Edge(2, 3), new Edge(3, 1)
            };
            undirectedGraphs[2] = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 10);
            undirectedGraphs[3] = new AdjacencyMatrixGraph(false, 10)
            {
                new Edge(0, 1), new Edge(0, 2), new Edge(0, 3), new Edge(2, 4), new Edge(2, 5), new Edge(2, 6),
                new Edge(5, 7), new Edge(5, 8), new Edge(5, 9), new Edge(8, 2)
            };
            rgg.SetSeed(444);
            undirectedGraphs[4] = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.2);
            rgg.SetSeed(555);
            undirectedGraphs[5] = rgg.TreeGraph(typeof(AdjacencyListsGraph <SimpleAdjacencyList>), 1000, 1.0);

            TestSet findCycleUndirected = new TestSet();

            findCycleUndirected.TestCases.Add(new FindCycleTestCase(5, null, undirectedGraphs[0], true));
            findCycleUndirected.TestCases.Add(new FindCycleTestCase(5, null, undirectedGraphs[1], true));
            findCycleUndirected.TestCases.Add(new FindCycleTestCase(5, null, undirectedGraphs[2], false));
            findCycleUndirected.TestCases.Add(new FindCycleTestCase(5, null, undirectedGraphs[3], true));
            findCycleUndirected.TestCases.Add(new FindCycleTestCase(5, null, undirectedGraphs[4], true));
            findCycleUndirected.TestCases.Add(new FindCycleTestCase(5, null, undirectedGraphs[5], false));

            Graph[] trees = new Graph[10];
            trees[0] = new AdjacencyListsGraph <AVLAdjacencyList>(false, 3)
            {
                new Edge(0, 1), new Edge(1, 2)
            };
            trees[1] = new AdjacencyListsGraph <SimpleAdjacencyList>(false, 4)
            {
                new Edge(0, 1), new Edge(1, 2), new Edge(2, 3)
            };
            trees[2] = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 1);
            trees[3] = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 2)
            {
                new Edge(0, 1)
            };
            trees[4] = new AdjacencyMatrixGraph(false, 5)
            {
                new Edge(1, 3), new Edge(2, 4)
            };
            trees[5] = new AdjacencyMatrixGraph(true, 3)
            {
                new Edge(0, 1), new Edge(0, 2)
            };
            rgg.SetSeed(777);
            trees[6] = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.2);
            rgg.SetSeed(888);
            trees[7] = rgg.TreeGraph(typeof(AdjacencyListsGraph <SimpleAdjacencyList>), 1000, 1.0);
            rgg.SetSeed(999);
            trees[8] = rgg.TreeGraph(typeof(AdjacencyListsGraph <SimpleAdjacencyList>), 1001, 1.0);
            trees[9] = new AdjacencyListsGraph <SimpleAdjacencyList>(false, 10);
            for (int i = 1; i < 10; ++i)
            {
                trees[9].AddEdge(i - 1, i);
            }

            TestSet treeCenter = new TestSet();

            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[0], true, new int[] { 1 }));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[1], true, new int[] { 1, 2 }));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[2], true, new int[] { 0 }));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[3], true, new int[] { 0, 1 }));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[4], false, null));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, new ArgumentException(), trees[5], false, null));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[6], false, null));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[7], true, new int[] { 305, 786 }));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[8], true, new int[] { 60 }));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[9], true, new int[] { 4, 5 }));

            //
            // Odkomentuj odpowiednią linię aby zobaczyć wybrany graf
            // Pamiętaj, że przykłady numerowane są od 1
            //
//        ge.Export(directedGraphs[0]);
//        ge.Export(directedGraphs[1]);
//        ge.Export(directedGraphs[2]);
//        ge.Export(directedGraphs[3]);
//        ge.Export(directedGraphs[4]);
//        ge.Export(directedGraphs[5]);
//        ge.Export(directedGraphs[6]);
//        ge.Export(directedGraphs[7]);
//        ge.Export(undirectedGraphs[0]);
//        ge.Export(undirectedGraphs[1]);
//        ge.Export(undirectedGraphs[2]);
//        ge.Export(undirectedGraphs[3]);
//        ge.Export(undirectedGraphs[4]);
//        ge.Export(undirectedGraphs[5]);
//        ge.Export(trees[0]);
//        ge.Export(trees[1]);
//        ge.Export(trees[2]);
//        ge.Export(trees[3]);
//        ge.Export(trees[4]);
//        ge.Export(trees[5]);
//        ge.Export(trees[6]);
//        ge.Export(trees[7]);
//        ge.Export(trees[8]);

            Console.WriteLine("\nCycle Finding\n");

            FindCycleTestCase.ResultOnly = true;
            Console.WriteLine("\nDirected Graphs - result only");
            findCycleDirected.PreformTests(verbose: true, checkTimeLimit: false);
            Console.WriteLine("\nUndirected Graphs - result only");
            findCycleUndirected.PreformTests(verbose: true, checkTimeLimit: false);

            FindCycleTestCase.ResultOnly = false;
            Console.WriteLine("\nDirected Graphs - full funcionality");
            findCycleDirected.PreformTests(verbose: true, checkTimeLimit: false, forceExecution: false);
            Console.WriteLine("\nUndirected Graphs - full funcionality");
            findCycleUndirected.PreformTests(verbose: true, checkTimeLimit: false, forceExecution: false);

            Console.WriteLine("\nTree Center\n");
            TreeCenterTestCase.ResultOnly = true;
            Console.WriteLine("\nResult only");
            treeCenter.PreformTests(verbose: true, checkTimeLimit: false);
            Console.WriteLine("\nFull funcionality");
            TreeCenterTestCase.ResultOnly = false;
            treeCenter.PreformTests(verbose: true, checkTimeLimit: false, forceExecution: false);
        }
コード例 #16
0
    public static void Main()
    {
        Graph g1, g2;
        ulong licz;
        int   cc;
        int   orda = 0;

        int[] ord = null;    // kolejnosc odwiedzania wierzcholkow

        // metoda wykorzystywana do numerowania wierzchołków
        Predicate <int> vv = delegate(int n)
        {
            Console.WriteLine(n);
            ord[n] = ++orda;
            return(true);
        };

        // przykładowy graf w reprezentacji macierzowej
        g1 = new AdjacencyMatrixGraph(false, 15);
        g1.AddEdge(0, 1, 3);
        g1.AddEdge(0, 4, 5);
        g1.AddEdge(1, 4, 6);
        g1.AddEdge(1, 5, 4);
        g1.AddEdge(2, 6, 5);
        g1.AddEdge(4, 7, 8);
        g1.AddEdge(4, 8, 2);
        g1.AddEdge(4, 10, 12);
        g1.AddEdge(5, 8, 1);
        g1.AddEdge(5, 9, 7);
        g1.AddEdge(6, 11, 4);
        g1.AddEdge(6, 14, 5);
        g1.AddEdge(7, 8, 9);
        g1.AddEdge(8, 12, 3);
        g1.AddEdge(10, 12, 2);
        g1.AddEdge(10, 13, 3);
        Graph.Write(g1, "graf15.xml");
        Console.WriteLine();

        Console.WriteLine("algorytm rekurencyjny");
        Console.WriteLine("przeszukiwanie grafu w głąb i numerowanie wierzchołków");
        Console.WriteLine("graf w reprezentacji macierzowej");
        Console.WriteLine();
        ord  = new int[g1.VerticesCount];
        orda = 0;
        licz = Graph.Counter;
        g1.DFSearchAll(vv, null, out cc);
        Console.WriteLine("\nSpojne skladowe:  {0}", cc);
        Console.WriteLine("Liczba odwolan:  {0,3}\n", Graph.Counter - licz);
        for (int i = 0; i < g1.VerticesCount; ++i)
        {
            Console.WriteLine("  {0}  {1}", i, ord[i]);
        }
        Console.WriteLine();

        // ten sam graf w reprezentacji listowej (tablice haszowane)
        g2 = Graph.Read(typeof(AdjacencyListsGraph <HashTableAdjacencyList>), "Graf15.xml");

        Console.WriteLine("algorytm rekurencyjny");
        Console.WriteLine("przeszukiwanie grafu w głąb i numerowanie wierzchołków");
        Console.WriteLine("graf w reprezentacji listowej (tablice haszowane)");
        Console.WriteLine();
        ord  = new int[g2.VerticesCount];
        orda = 0;
        licz = Graph.Counter;
        g2.DFSearchAll(vv, null, out cc);
        Console.WriteLine("\nSpojne skladowe:  {0}", cc);
        Console.WriteLine("Liczba odwolan:  {0,3}\n", Graph.Counter - licz);
        for (int i = 0; i < g2.VerticesCount; ++i)
        {
            Console.WriteLine("  {0}  {1}", i, ord[i]);
        }
        Console.WriteLine();

        Console.WriteLine("algorytm ogólny z wykorzystaniem stosu");
        Console.WriteLine("przeszukiwanie grafu w głąb i numerowanie wierzchołków");
        Console.WriteLine("graf w reprezentacji macierzowej");
        Console.WriteLine();
        ord  = new int[g1.VerticesCount];
        orda = 0;
        licz = Graph.Counter;
        g1.GeneralSearchAll <EdgesStack>(vv, null, out cc);
        Console.WriteLine("\nSpojne skladowe:  {0}", cc);
        Console.WriteLine("Liczba odwolan:  {0,3}\n", Graph.Counter - licz);
        for (int i = 0; i < g1.VerticesCount; ++i)
        {
            Console.WriteLine("  {0}  {1}", i, ord[i]);
        }
        Console.WriteLine();

        // wyświetlenie grafu
        GraphExport ge = new GraphExport();

        ge.Export(g1);
    }
コード例 #17
0
    public static void Main()
    {
        var ge  = new GraphExport();
        var rgg = new RandomGraphGenerator(123);

        int[]    order;
        string[] desc;
        int[]    ec = new int[3];

        Graph g = new AdjacencyMatrixGraph(false, 5);

        g.AddEdge(0, 1);
        g.AddEdge(0, 4);
        g.AddEdge(1, 2);
        g.AddEdge(2, 0);
        g.AddEdge(2, 3);
        g.AddEdge(3, 4);
        g.AddEdge(4, 3);
        ge.Export(g, null, "G");

        Graph lg = Lab03.LineGraph(g, out desc);

        ge.Export(lg, desc, "LG");

        Graph[] g2 = new Graph[3];
        g2[0] = new AdjacencyMatrixGraph(true, 4);
        g2[0].AddEdge(0, 1);
        g2[0].AddEdge(0, 3);
        g2[0].AddEdge(1, 2);
        g2[0].AddEdge(3, 2);

        g2[1] = rgg.DAG(typeof(AdjacencyMatrixGraph), 100, 0.9, 1, 1);
        g2[2] = rgg.DAG(typeof(AdjacencyListsGraph <SimplyAdjacencyList>), 1000, 0.2, 1, 1);

        ec[0] = g2[0].EdgesCount;
        ec[1] = g2[1].EdgesCount;
        ec[2] = g2[2].EdgesCount;

        Console.WriteLine("Sortowanie topologiczne - DFS");
        for (int i = 0; i < 3; ++i)
        {
            order = Lab03.TopologicalSort_DFS(g2[i]);
            Console.WriteLine("  test {0} : {1}", i, TopologicalSortTest(g2[i], order));
        }

        if (ec[0] != g2[0].EdgesCount || ec[1] != g2[1].EdgesCount || ec[2] != g2[2].EdgesCount)
        {
            Console.WriteLine("  Blad - zmieniono graf");
        }

        ec[0] = g2[0].EdgesCount;
        ec[1] = g2[1].EdgesCount;
        ec[2] = g2[2].EdgesCount;

        Console.WriteLine("Sortowanie topologiczne - zrodla 1");
        for (int i = 0; i < 3; ++i)
        {
            order = Lab03.TopologicalSort_V0(g2[i]);
            Console.WriteLine("  test {0} : {1}", i, TopologicalSortTest(g2[i], order));
        }

        if (ec[0] != g2[0].EdgesCount || ec[1] != g2[1].EdgesCount || ec[2] != g2[2].EdgesCount)
        {
            Console.WriteLine("  Blad - zmieniono graf");
        }

        Graph[] g3 = new Graph[3];
        g3[0] = g2[0].Clone();
        g3[0].AddEdge(1, 0);
        g3[1] = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.9, 1, 1);
        g3[2] = rgg.DirectedGraph(typeof(AdjacencyListsGraph <SimplyAdjacencyList>), 1000, 0.2, 1, 1);

        ec[0] = g3[0].EdgesCount;
        ec[1] = g3[1].EdgesCount;
        ec[2] = g3[2].EdgesCount;

        Console.WriteLine("Sortowanie topologiczne - zrodla 2");
        for (int i = 0; i < 3; ++i)
        {
            order = Lab03.TopologicalSort_V0(g3[i]);
            Console.WriteLine("  test {0} : {1}", i, order == null);
        }

        if (ec[0] != g3[0].EdgesCount || ec[1] != g3[1].EdgesCount || ec[2] != g3[2].EdgesCount)
        {
            Console.WriteLine("  Blad - zmieniono graf");
        }
    }
コード例 #18
0
        public static void Image(this Graph g)
        {
            GraphExport graphExport = new GraphExport(true, null, "chrome", "", null);

            graphExport.Export(g);
        }
コード例 #19
0
ファイル: AirlinePlanner.cs プロジェクト: L-Dogg/ASD2
        // Możesz dodać nowe składowe


        public AirlinePlanner(string path, int n)
        {
            num = n;
            ge  = new GraphExport(false, path);
        }
コード例 #20
0
 public Pathfinder(Graph roads, int[] cityCosts)
 {
     RoadsGraph  = roads;
     CityCosts   = cityCosts;
     graphExport = new GraphExport();
 }
コード例 #21
0
ファイル: Program.cs プロジェクト: DarkAlek/Tajo
        static void Main(string[] args)
        {
            DateTime startTime, endTime;
            char     x = '0';
            char     y = '0';
            Dictionary <int, int> output1;
            Dictionary <int, int> output2;

            GraphExport ge = null;

            try
            {
                ge = new GraphExport();
            }
            catch
            {
                Console.WriteLine("GraphViz isn't installed. Graphs will be not visualized.");
            }

            // Load *.csv with Open Dialog
            OpenFileDialog ofd1 = new OpenFileDialog();

            ofd1.ShowDialog();
            var path_input1 = ofd1.FileName;

            OpenFileDialog ofd2 = new OpenFileDialog();

            ofd2.ShowDialog();
            var path_input2 = ofd2.FileName;

            if (path_input1 == "" || path_input2 == "")
            {
                return;
            }

            Console.WriteLine("Reading graphs from .csv...");
            var graph1           = GraphReader.ReadCSV(path_input1);
            var graph2           = GraphReader.ReadCSV(path_input2);
            CommonGraphSolver gs = new CommonGraphSolver(graph1, graph2);
            var modularGraph     = gs.ModularProductGraphVertices;

            bool flag = true;

            while (flag)
            {
                Console.WriteLine("---------------------------------------------------------");
                Console.WriteLine("TAJO maximal common subgraph project.");
                Console.WriteLine("Press 1 to run exact algorithm.");
                Console.WriteLine("Press 2 to run approximate algorithm no.1");
                Console.WriteLine("Press 3 to run approximate algorithm no.2");
                Console.WriteLine("---------------------------------------------------------");

                var inputString = Console.ReadLine();
                try
                {
                    x = inputString[0];
                }
                catch
                {
                    x = '0';
                }

                if (x == '1')
                {
                    Console.WriteLine("Press relevant key to choose exact alghoritm version:");
                    Console.WriteLine(" 1) Vertices");
                    Console.WriteLine(" 2) Vertices + Edges");
                    inputString = Console.ReadLine();
                    try
                    {
                        y = inputString[0];
                    }
                    catch
                    {
                        y = '0';
                    }
                }

                // TODO: Visualize result common graphs
                // visualize graphs
                //ge.Export(gs.Graph1);
                //ge.Export(gs.Graph2);
                //ge.Export(gs.ModularProductGraphVertices);

                var path_output1 = path_input1.Remove(path_input1.Length - 12) + "result1";
                var path_output2 = path_input1.Remove(path_input2.Length - 12) + "result2";

                switch (x)
                {
                case '1':
                    if (y == '1')
                    {
                        Console.WriteLine("Exact algorithm - computing vertices...");
                        startTime = DateTime.Now;
                        output1   = gs.ExactAlghoritmVertices();
                        endTime   = DateTime.Now;
                        if (output1 != null)
                        {
                            GraphReader.WriteCSV(path_output1, 1, output1);
                        }
                        Console.WriteLine(endTime - startTime);
                        if (graph1.VerticesCount <= 30 && graph2.VerticesCount <= 30)
                        {
                            VisualizeResultGraphs(ge, graph1, graph2, output1);
                        }
                    }
                    else if (y == '2')
                    {
                        Console.WriteLine("Exact algorithm - computing vertices + edges...");
                        startTime = DateTime.Now;
                        output2   = gs.ExactAlghoritmVerticesEdges();
                        endTime   = DateTime.Now;
                        if (output2 != null)
                        {
                            GraphReader.WriteCSV(path_output2, 1, output2);
                        }
                        Console.WriteLine(endTime - startTime);
                        if (graph1.VerticesCount <= 30 && graph2.VerticesCount <= 30)
                        {
                            VisualizeResultGraphs(ge, graph1, graph2, output2);
                        }
                    }
                    break;

                case '2':
                    Console.WriteLine("ApproximateAlgorithm1 - computing...");
                    startTime = DateTime.Now;
                    output1   = gs.ApproximateAlgorithm1();
                    endTime   = DateTime.Now;
                    if (output1 != null)
                    {
                        GraphReader.WriteCSV(path_output1, 2, output1);
                    }
                    Console.WriteLine(endTime - startTime);
                    if (graph1.VerticesCount <= 30 && graph2.VerticesCount <= 30)
                    {
                        VisualizeResultGraphs(ge, graph1, graph2, output1);
                    }
                    break;

                case '3':
                    Console.WriteLine("ApproximateAlgorithm2 - computing...");
                    startTime = DateTime.Now;
                    output1   = gs.ApproximateAlgorithm2();
                    endTime   = DateTime.Now;
                    if (output1 != null)
                    {
                        GraphReader.WriteCSV(path_output1, 3, output1);
                    }
                    Console.WriteLine(endTime - startTime);
                    if (graph1.VerticesCount <= 30 && graph2.VerticesCount <= 30)
                    {
                        VisualizeResultGraphs(ge, graph1, graph2, output1);
                    }
                    break;

                default:
                    break;
                }
                Console.WriteLine("---------------------------------------------------------");
                Console.WriteLine("Press [ESC] to exit...");
                Console.WriteLine("Press [BACKSPACE] to load new graphs...");
                Console.WriteLine("Press any other button to contiune calculations on given graphs...");
                var keyPressed = Console.ReadKey();
                if (keyPressed.Key == ConsoleKey.Backspace)
                {
                    ofd1 = new OpenFileDialog();
                    ofd1.ShowDialog();
                    path_input1 = ofd1.FileName;

                    ofd2 = new OpenFileDialog();
                    ofd2.ShowDialog();
                    path_input2 = ofd2.FileName;

                    if (path_input1 == "" || path_input2 == "")
                    {
                        return;
                    }

                    Console.WriteLine("Reading graphs from .csv...");
                    graph1       = GraphReader.ReadCSV(path_input1);
                    graph2       = GraphReader.ReadCSV(path_input2);
                    gs           = new CommonGraphSolver(graph1, graph2);
                    modularGraph = gs.ModularProductGraphVertices;
                }
                if (keyPressed.Key == ConsoleKey.Escape)
                {
                    flag = false;
                }
            }
        }
コード例 #22
0
ファイル: ConstructTree.cs プロジェクト: L-Dogg/ASD2
    public static void Main()
    {
        Graph g, t1, t2, t3, t4;
        int   cc;
        int   treeweight = 0;

        bool[] visited = null;
        int[]  from    = null;
        Graph  tree    = null;
        string msg;

        // metoda wykorzystywana do konstruowania drzewa
        // związanego z odpowiednim algorytmem przeszukiwania
        Predicate <Edge> ConstructTree = delegate(Edge e)
        {
            if (!visited[e.From])
            {
                visited[e.From] = true;
            }
            if (!visited[e.To])
            {
                treeweight += e.Weight;
                tree.AddEdge(e);
                visited[e.To] = true;
            }
            return(true);
        };

        // metoda wykorzystywana do sprawdzania
        // czy dany graf jest drzewem
        Predicate <Edge> IsTree = delegate(Edge e)
        {
            if (!visited[e.From])
            {
                visited[e.From] = true;
                from[e.From]    = e.From;
            }
            if (visited[e.To] && e.To != from[e.From])
            {
                return(false);
            }
            visited[e.To] = true;
            from[e.To]    = e.From;
            return(true);
        };

        // przykładowy graf
        g = new AdjacencyMatrixGraph(false, 15);
        g.AddEdge(0, 1, 3);
        g.AddEdge(0, 4, 5);
        g.AddEdge(1, 4, 6);
        g.AddEdge(1, 5, 4);
        g.AddEdge(2, 6, 5);
        g.AddEdge(4, 7, 8);
        g.AddEdge(4, 8, 2);
        g.AddEdge(4, 10, 12);
        g.AddEdge(5, 8, 1);
        g.AddEdge(5, 9, 7);
        g.AddEdge(6, 11, 4);
        g.AddEdge(6, 14, 5);
        g.AddEdge(7, 8, 9);
        g.AddEdge(8, 12, 3);
        g.AddEdge(10, 12, 2);
        g.AddEdge(10, 13, 3);

        // konstruowanie drzewa związanego z przeszukiwaniem w głąb
        // (algorytm korzysta ze stosu krawędzi)
        treeweight = 0;
        visited    = new bool[g.VerticesCount];
        tree       = g.IsolatedVerticesGraph();
        g.GeneralSearchAll <EdgesStack>(null, ConstructTree, out cc);
        t1 = tree;
        Console.WriteLine("Stos        - waga drzewa: {0,3}", treeweight);

        // konstruowanie drzewa związanego z przeszukiwaniem wszerz
        // (algorytm korzysta z kolejki krawędzi)
        treeweight = 0;
        visited    = new bool[g.VerticesCount];
        tree       = g.IsolatedVerticesGraph();
        g.GeneralSearchAll <EdgesQueue>(null, ConstructTree, out cc);
        t2 = tree;
        Console.WriteLine("Kolejka     - waga drzewa: {0,3}", treeweight);

        // konstruowanie minimalnego drzewa rozpinającego
        // (algorytm korzysta z kolejki priorytetowej krawędzi, priorytet minimalna waga)
        // jest to algorytm Prima
        treeweight = 0;
        visited    = new bool[g.VerticesCount];
        tree       = g.IsolatedVerticesGraph();
        g.GeneralSearchAll <EdgesMinPriorityQueue>(null, ConstructTree, out cc);
        t3 = tree;
        Console.WriteLine("Kolejka Min - waga drzewa: {0,3}", treeweight);

        // konstruowanie maksymalnego drzewa rozpinającego
        // (algorytm korzysta z kolejki priorytetowej krawędzi, priorytet maksymalna waga)
        treeweight = 0;
        visited    = new bool[g.VerticesCount];
        tree       = g.IsolatedVerticesGraph();
        g.GeneralSearchAll <EdgesMaxPriorityQueue>(null, ConstructTree, out cc);
        t4 = tree;
        Console.WriteLine("Kolejka Max - waga drzewa: {0,3}", treeweight);

        // sprawdzanie czy wyjściowy graf jest drzewem - nie jest
        visited = new bool[g.VerticesCount];
        from    = new int[g.VerticesCount];
        msg     = g.GeneralSearchAll <EdgesQueue>(null, IsTree, out cc) ? "jest" : "nie jest";
        Console.WriteLine("Graf g {0} drzewem (lasem)", msg);

        // potwierdzenie, że pierwsze skonstruowane drzewo rzeczywiście jest drzewem
        visited = new bool[g.VerticesCount];
        from    = new int[g.VerticesCount];
        msg     = t1.GeneralSearchAll <EdgesQueue>(null, IsTree, out cc) ? "jest" : "nie jest";
        Console.WriteLine("Graf t1 {0} drzewem (lasem)", msg);

        // potwierdzenie, że drugie skonstruowane drzewo rzeczywiście jest drzewem
        visited = new bool[g.VerticesCount];
        from    = new int[g.VerticesCount];
        msg     = t2.GeneralSearchAll <EdgesQueue>(null, IsTree, out cc) ? "jest" : "nie jest";
        Console.WriteLine("Graf t2 {0} drzewem (lasem)", msg);

        // potwierdzenie, że trzecie skonstruowane drzewo rzeczywiście jest drzewem
        visited = new bool[g.VerticesCount];
        from    = new int[g.VerticesCount];
        msg     = t3.GeneralSearchAll <EdgesQueue>(null, IsTree, out cc) ? "jest" : "nie jest";
        Console.WriteLine("Graf t3 {0} drzewem (lasem)", msg);

        // potwierdzenie, że czwarte skonstruowane drzewo rzeczywiście jest drzewem
        visited = new bool[g.VerticesCount];
        from    = new int[g.VerticesCount];
        msg     = t4.GeneralSearchAll <EdgesQueue>(null, IsTree, out cc) ? "jest" : "nie jest";
        Console.WriteLine("Graf t4 {0} drzewem (lasem)", msg);

        // wyświetlanie grafu wyjściowego i skonstruowanych drzew
        GraphExport ge = new GraphExport();

        ge.Export(g, null, "Graph");
        ge.Export(t1, null, "StackTree");
        ge.Export(t2, null, "QueueTree");
        ge.Export(t3, null, "MinQueueTree");
        ge.Export(t4, null, "MaxQueueTree");
    }
コード例 #23
0
ファイル: Lab03_Main.cs プロジェクト: magierska/AiSD2
        static void Main(string[] args)
        {
            GraphExport          ge  = new GraphExport();
            RandomGraphGenerator rgg = new RandomGraphGenerator();

            Graph[] directedGraphs = new Graph[8];
            directedGraphs[0] = new AdjacencyListsGraph <AVLAdjacencyList>(true, 3)
            {
                new Edge(0, 1), new Edge(1, 2), new Edge(2, 0)
            };
            directedGraphs[1] = new AdjacencyListsGraph <SimpleAdjacencyList>(true, 3)
            {
                new Edge(0, 1), new Edge(1, 2), new Edge(2, 1)
            };
            directedGraphs[2] = new AdjacencyMatrixGraph(true, 4)
            {
                new Edge(0, 1), new Edge(0, 2), new Edge(1, 3), new Edge(2, 3)
            };
            directedGraphs[3] = new AdjacencyListsGraph <HashTableAdjacencyList>(true, 10);
            directedGraphs[4] = new AdjacencyMatrixGraph(true, 10)
            {
                new Edge(0, 1), new Edge(0, 2), new Edge(0, 3), new Edge(2, 4), new Edge(2, 5), new Edge(2, 6),
                new Edge(5, 7), new Edge(5, 8), new Edge(5, 9), new Edge(6, 5), new Edge(7, 8), new Edge(8, 2)
            };
            rgg.SetSeed(111);
            directedGraphs[5] = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.2);
            rgg.SetSeed(222);
            directedGraphs[6] = rgg.DirectedCycle(typeof(AdjacencyListsGraph <SimpleAdjacencyList>), 1000);
            rgg.SetSeed(333);
            directedGraphs[7] = rgg.DAG(typeof(AdjacencyMatrixGraph), 200, 0.2, 1, 1);

            TestSet findCycleDirected = new TestSet();

            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[0], true));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[1], true));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[2], false));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[3], false));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[4], true));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[5], true));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[6], true));
            findCycleDirected.TestCases.Add(new FindCycleTestCase(5, null, directedGraphs[7], false));

            Graph[] undirectedGraphs = new Graph[6];
            undirectedGraphs[0] = new AdjacencyListsGraph <AVLAdjacencyList>(false, 3)
            {
                new Edge(0, 1), new Edge(1, 2), new Edge(2, 0)
            };
            undirectedGraphs[1] = new AdjacencyListsGraph <SimpleAdjacencyList>(false, 4)
            {
                new Edge(0, 1), new Edge(1, 2), new Edge(2, 3), new Edge(3, 1)
            };
            undirectedGraphs[2] = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 10);
            undirectedGraphs[3] = new AdjacencyMatrixGraph(false, 10)
            {
                new Edge(0, 1), new Edge(0, 2), new Edge(0, 3), new Edge(2, 4), new Edge(2, 5), new Edge(2, 6),
                new Edge(5, 7), new Edge(5, 8), new Edge(5, 9), new Edge(8, 2)
            };
            rgg.SetSeed(444);
            undirectedGraphs[4] = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.2);
            rgg.SetSeed(555);
            undirectedGraphs[5] = rgg.TreeGraph(typeof(AdjacencyListsGraph <SimpleAdjacencyList>), 1000, 1.0);

            TestSet findCycleUndirected = new TestSet();

            findCycleUndirected.TestCases.Add(new FindCycleTestCase(5, null, undirectedGraphs[0], true));
            findCycleUndirected.TestCases.Add(new FindCycleTestCase(5, null, undirectedGraphs[1], true));
            findCycleUndirected.TestCases.Add(new FindCycleTestCase(5, null, undirectedGraphs[2], false));
            findCycleUndirected.TestCases.Add(new FindCycleTestCase(5, null, undirectedGraphs[3], true));
            findCycleUndirected.TestCases.Add(new FindCycleTestCase(5, null, undirectedGraphs[4], true));
            findCycleUndirected.TestCases.Add(new FindCycleTestCase(5, null, undirectedGraphs[5], false));

            Graph[] trees = new Graph[10];
            trees[0] = new AdjacencyListsGraph <AVLAdjacencyList>(false, 3)
            {
                new Edge(0, 1), new Edge(1, 2)
            };
            trees[1] = new AdjacencyListsGraph <SimpleAdjacencyList>(false, 4)
            {
                new Edge(0, 1), new Edge(1, 2), new Edge(2, 3)
            };
            trees[2] = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 1);
            trees[3] = new AdjacencyListsGraph <HashTableAdjacencyList>(false, 2)
            {
                new Edge(0, 1)
            };
            trees[4] = new AdjacencyMatrixGraph(false, 5)
            {
                new Edge(1, 3), new Edge(2, 4)
            };
            trees[5] = new AdjacencyMatrixGraph(true, 3)
            {
                new Edge(0, 1), new Edge(0, 2)
            };
            rgg.SetSeed(777);
            trees[6] = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.2);
            rgg.SetSeed(888);
            trees[7] = rgg.TreeGraph(typeof(AdjacencyListsGraph <SimpleAdjacencyList>), 1000, 1.0);
            rgg.SetSeed(999);
            trees[8] = rgg.TreeGraph(typeof(AdjacencyListsGraph <SimpleAdjacencyList>), 1001, 1.0);
            trees[9] = new AdjacencyListsGraph <SimpleAdjacencyList>(false, 10);
            for (int i = 1; i < 10; ++i)
            {
                trees[9].AddEdge(i - 1, i);
            }

            TestSet treeCenter = new TestSet();

            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[0], true, new int[] { 1 }));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[1], true, new int[] { 1, 2 }));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[2], true, new int[] { 0 }));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[3], true, new int[] { 0, 1 }));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[4], false, null));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, new ArgumentException(), trees[5], false, null));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[6], false, null));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[7], true, new int[] { 305, 786 }));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[8], true, new int[] { 60 }));
            treeCenter.TestCases.Add(new TreeCenterTestCase(5, null, trees[9], true, new int[] { 4, 5 }));

            //
            // Odkomentuj odpowiednią linię aby zobaczyć wybrany graf
            // Pamiętaj, że przykłady numerowane są od 1
            //
            //ge.Export(directedGraphs[0]);
            //ge.Export(directedGraphs[1]);
            //ge.Export(directedGraphs[2]);
            //ge.Export(directedGraphs[3]);
            //ge.Export(directedGraphs[4]);
            //ge.Export(directedGraphs[5]);
            //ge.Export(directedGraphs[6]);
            //ge.Export(directedGraphs[7]);
            //ge.Export(undirectedGraphs[0]);
            //ge.Export(undirectedGraphs[1]);
            //ge.Export(undirectedGraphs[2]);
            ge.Export(undirectedGraphs[3]);
            //ge.Export(undirectedGraphs[4]);
            //ge.Export(undirectedGraphs[5]);
            //ge.Export(trees[0]);
            //ge.Export(trees[1]);
            //ge.Export(trees[2]);
            //ge.Export(trees[3]);
            //ge.Export(trees[4]);
            //ge.Export(trees[5]);
            //ge.Export(trees[6]);
            //ge.Export(trees[7]);
            //ge.Export(trees[8]);

            long[]    timeElapsed = new long[9];
            Stopwatch stopwatch   = new Stopwatch();


            Console.WriteLine("\nCycle Finding\n");

            FindCycleTestCase.ResultOnly = true;
            Console.WriteLine("\nDirected Graphs - result only");
            stopwatch.Start();
            findCycleDirected.PreformTests(verbose: true, checkTimeLimit: false);
            stopwatch.Stop();
            timeElapsed[0] = stopwatch.ElapsedMilliseconds;
            Console.WriteLine("\nUndirected Graphs - result only");
            stopwatch.Restart();
            findCycleUndirected.PreformTests(verbose: true, checkTimeLimit: false);
            stopwatch.Stop();
            timeElapsed[1] = stopwatch.ElapsedMilliseconds;

            FindCycleTestCase.ResultOnly = false;
            Console.WriteLine("\nDirected Graphs - full funcionality");
            stopwatch.Restart();
            findCycleDirected.PreformTests(verbose: true, checkTimeLimit: false, forceExecution: false);
            stopwatch.Stop();
            timeElapsed[2] = stopwatch.ElapsedMilliseconds;
            Console.WriteLine("\nUndirected Graphs - full funcionality");
            stopwatch.Restart();
            findCycleUndirected.PreformTests(verbose: true, checkTimeLimit: false, forceExecution: false);
            stopwatch.Stop();
            timeElapsed[3] = stopwatch.ElapsedMilliseconds;

            Console.WriteLine("\nTree Center\n");
            TreeCenterTestCase.ResultOnly = true;
            Console.WriteLine("\nResult only");
            stopwatch.Restart();
            treeCenter.PreformTests(verbose: true, checkTimeLimit: false);
            stopwatch.Stop();
            timeElapsed[4] = stopwatch.ElapsedMilliseconds;
            Console.WriteLine("\nFull funcionality");
            TreeCenterTestCase.ResultOnly = false;

            stopwatch.Restart();
            treeCenter.PreformTests(verbose: true, checkTimeLimit: false, forceExecution: false);
            stopwatch.Stop();
            timeElapsed[5] = stopwatch.ElapsedMilliseconds;

            Console.WriteLine("\n\nPerformance metrics for the initial task tests");
            for (int i = 0; i < 6; i++)
            {
                Console.WriteLine("Testset {0}: {1,5} ms", i + 1, timeElapsed[i]);
            }



            // Nie radzę tych grafów próbować eksportować za pomocą GraphViz (mają sporo wierzchołków)
            // Wyjątek stanowi customTrees[0]
            Console.WriteLine("\n\nCustom tests");
            Console.WriteLine("Generating graphs. This may take a while");

            // Cycle in directed graphs
            Graph[] customDirectedGraphs = new Graph[5];
            customDirectedGraphs[0] = rgg.DirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.7);
            customDirectedGraphs[1] = rgg.DAG(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1000, 0.9, 1, 1);
            customDirectedGraphs[2] = rgg.DirectedCycle(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1000);
            customDirectedGraphs[3] = rgg.DirectedGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1000, 0.5);
            customDirectedGraphs[4] = rgg.DirectedGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1000, 0.7);

            TestSet customDirectedGraphsTestSet = new TestSet();

            customDirectedGraphsTestSet.TestCases.Add(new FindCycleTestCase(5, null, customDirectedGraphs[0], true));
            customDirectedGraphsTestSet.TestCases.Add(new FindCycleTestCase(5, null, customDirectedGraphs[1], false));
            customDirectedGraphsTestSet.TestCases.Add(new FindCycleTestCase(5, null, customDirectedGraphs[2], true));
            customDirectedGraphsTestSet.TestCases.Add(new FindCycleTestCase(5, null, customDirectedGraphs[3], true));
            customDirectedGraphsTestSet.TestCases.Add(new FindCycleTestCase(5, null, customDirectedGraphs[4], true));


            // Cycle in undirected graphs
            Graph[] customUndirectedGraphs = new Graph[5];
            customUndirectedGraphs[0] = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.7);
            customUndirectedGraphs[1] = rgg.TreeGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1000, 1);
            customUndirectedGraphs[2] = rgg.UndirectedCycle(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1000);
            customUndirectedGraphs[3] = rgg.UndirectedGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1000, 0.5);
            customUndirectedGraphs[4] = rgg.UndirectedGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1000, 0.7);

            TestSet customUndirectedGraphsTestSet = new TestSet();

            customUndirectedGraphsTestSet.TestCases.Add(new FindCycleTestCase(5, null, customUndirectedGraphs[0], true));
            customUndirectedGraphsTestSet.TestCases.Add(new FindCycleTestCase(5, null, customUndirectedGraphs[1], false));
            customUndirectedGraphsTestSet.TestCases.Add(new FindCycleTestCase(5, null, customUndirectedGraphs[2], true));
            customUndirectedGraphsTestSet.TestCases.Add(new FindCycleTestCase(5, null, customUndirectedGraphs[3], true));
            customUndirectedGraphsTestSet.TestCases.Add(new FindCycleTestCase(5, null, customUndirectedGraphs[4], true));

            // Tree center
            Graph[] customTrees = new Graph[5];
            customTrees[0] = new AdjacencyMatrixGraph(false, 1);
            customTrees[1] = rgg.TreeGraph(typeof(AdjacencyMatrixGraph), 100, 0.5);
            customTrees[2] = rgg.TreeGraph(typeof(AdjacencyListsGraph <SimpleAdjacencyList>), 100, 1);
            customTrees[3] = rgg.TreeGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 1000, 1);
            customTrees[4] = rgg.TreeGraph(typeof(AdjacencyListsGraph <AVLAdjacencyList>), 10000, 1);

            TestSet customTreeSet = new TestSet();

            customTreeSet.TestCases.Add(new TreeCenterTestCase(5, null, customTrees[0], true, new int[] { 0 }));
            customTreeSet.TestCases.Add(new TreeCenterTestCase(5, null, customTrees[1], false, null));
            customTreeSet.TestCases.Add(new TreeCenterTestCase(5, null, customTrees[2], true, new int[] { 77 }));
            customTreeSet.TestCases.Add(new TreeCenterTestCase(5, null, customTrees[3], true, new int[] { 146, 282 }));
            customTreeSet.TestCases.Add(new TreeCenterTestCase(5, null, customTrees[4], true, new int[] { 6780, 8396 }));



            Console.WriteLine("Custom cycle finding in directed graphs");
            stopwatch.Restart();
            customDirectedGraphsTestSet.PreformTests(verbose: true, checkTimeLimit: false, forceExecution: false);
            stopwatch.Stop();
            timeElapsed[6] = stopwatch.ElapsedMilliseconds;

            Console.WriteLine("Custom cycle finding in undirected graphs");
            stopwatch.Restart();
            customUndirectedGraphsTestSet.PreformTests(verbose: true, checkTimeLimit: false, forceExecution: false);
            stopwatch.Stop();
            timeElapsed[7] = stopwatch.ElapsedMilliseconds;

            Console.WriteLine("Custom tree center");
            stopwatch.Restart();
            customTreeSet.PreformTests(verbose: true, checkTimeLimit: false, forceExecution: false);
            stopwatch.Stop();
            timeElapsed[8] = stopwatch.ElapsedMilliseconds;


            Console.WriteLine("\n\nPerformance metrics for the custom tests");
            for (int i = 6; i < timeElapsed.Length; i++)
            {
                Console.WriteLine("Testset {0}: {1,5} ms", i + 1, timeElapsed[i]);
            }
        }
コード例 #24
0
    public static void Main()
    {
        var ge  = new GraphExport();
        var rgg = new RandomGraphGenerator();

        int[] scc;
        int   n, w;

        string[] desc;
        int[]    sccc = { 8, 17, 1000 };
        IGraph   mst;

        int[] mstw = { 47, 3998, 40533 };


        IGraph g1 = new AdjacencyMatrixGraph(true, 16);

        g1.AddEdge(0, 5);
        g1.AddEdge(1, 0);
        g1.AddEdge(1, 2);
        g1.AddEdge(1, 7);
        g1.AddEdge(2, 3);
        g1.AddEdge(3, 1);
        g1.AddEdge(3, 7);
        g1.AddEdge(4, 15);
        g1.AddEdge(5, 4);
        g1.AddEdge(5, 6);
        g1.AddEdge(6, 7);
        g1.AddEdge(7, 6);
        g1.AddEdge(7, 8);
        g1.AddEdge(8, 9);
        g1.AddEdge(10, 3);
        g1.AddEdge(12, 13);
        g1.AddEdge(13, 14);
        g1.AddEdge(14, 12);
        g1.AddEdge(15, 0);

        IGraph g2 = new AdjacencyMatrixGraph(false, 15);

        g2.AddEdge(0, 1, 3);
        g2.AddEdge(0, 4, 5);
        g2.AddEdge(1, 4, 6);
        g2.AddEdge(1, 5, 4);
        g2.AddEdge(2, 6, 5);
        g2.AddEdge(4, 7, 8);
        g2.AddEdge(4, 8, 2);
        g2.AddEdge(4, 10, 12);
        g2.AddEdge(5, 8, 1);
        g2.AddEdge(5, 9, 7);
        g2.AddEdge(6, 11, 4);
        g2.AddEdge(6, 14, 5);
        g2.AddEdge(7, 8, 9);
        g2.AddEdge(8, 12, 3);
        g2.AddEdge(10, 12, 2);
        g2.AddEdge(10, 13, 3);

        IGraph[] scc_test = new IGraph[3];
        scc_test[0] = g1;
        rgg.SetSeed(500);
        scc_test[1] = rgg.DirectedGraph(typeof(AdjacencyListsGraph), 1000, 0.005);
        scc_test[2] = rgg.DAG(typeof(AdjacencyMatrixGraph), 1000, 0.3, 1, 1);

        IGraph[] mst_test = new IGraph[3];
        mst_test[0] = g2;
        mst_test[1] = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 100, 0.3, 1, 1000);
        mst_test[2] = rgg.UndirectedGraph(typeof(AdjacencyListsGraph), 1000, 0.03, 1, 1000);

        Console.WriteLine();
        for (int i = 0; i < scc_test.Length; ++i)
        {
            n = scc_test[i].Tarjan(out scc);
            Console.WriteLine("Liczba silnie spojnych skladowych: {0,4},    powinno byc {1,4}", n, sccc[i]);
            if (i > 0)
            {
                continue;
            }
            desc = new string[scc_test[i].VerticesCount];
            for (int v = 0; v < scc_test[i].VerticesCount; ++v)
            {
                desc[v] = string.Format("{0}:{1}", v, scc[v]);
            }
            ge.Export(scc_test[i], desc, "scc");
        }

        Console.WriteLine();
        for (int i = 0; i < mst_test.Length; ++i)
        {
            w = mst_test[i].Boruvka(out mst);
            Console.WriteLine("Waga minimalnego drzewa rozpinajacego: {0,5},    powinno byc {1,5}", w, mstw[i]);
            if (i > 0)
            {
                continue;
            }
            ge.Export(mst_test[i], null, "graph");
            ge.Export(mst, null, "mst");
        }

        Console.WriteLine();
    }
コード例 #25
0
        public override void VerifyTestCase(out Result resultCode, out string message, object settings = null)
        {
            if (result_graph == null)
            {
                message    = $"No solution";
                resultCode = Result.BadResult;
                return;
            }
            bool res = false;

            if (expected_colors_number != colors_number)
            {
                message    = $"Incorrect numbers of colors: {colors_number}, should be: {expected_colors_number}";
                resultCode = Result.BadResult;
                return;
            }
            if (expected_result_graph.EdgesCount == result_graph.EdgesCount)
            {
                if (expected_result_graph.IsEqual(result_graph))
                {
                    res = true;
                }
                else
                {
                    //tu sprawdzam czy zwrocone kolorowanie krawedzi jest poprawne
                    for (int i = 0; i < result_graph.VerticesCount; ++i)
                    {
                        foreach (Edge e1 in result_graph.OutEdges(i))
                        {
                            foreach (Edge e2 in result_graph.OutEdges(e1.To))
                            {
                                if (e1.From != e2.To && e1.Weight == e2.Weight)
                                {
                                    var ge = new GraphExport();
                                    ge.Export(result_graph, "Result");
                                    message    = $"Incorrect coloring. Edges [{e1.From}, {e1.To}] and [{e2.From}, {e2.To}] have the same color!";
                                    resultCode = Result.BadResult;
                                    return;
                                }
                                foreach (Edge e3 in result_graph.OutEdges(e2.To))
                                {
                                    if (!(e1.From == e3.From && e1.To == e3.To) && !(e1.From == e3.To && e1.To == e3.From) && e1.Weight == e3.Weight)
                                    {
                                        var ge = new GraphExport();
                                        ge.Export(result_graph, "Result");
                                        message    = $"Incorrect coloring. Edges [{e1.From}, {e1.To}] and [{e3.From}, {e3.To}] have the same color!";
                                        resultCode = Result.BadResult;
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (!res)
            {
                var ge = new GraphExport();
                ge.Export(expected_result_graph, "Expected");
                ge.Export(result_graph, "Result");
                message    = $"Incorrect result graph";
                resultCode = Result.BadResult;
                return;
            }
            resultCode = Result.Success;
            message    = "OK";
        }
コード例 #26
0
    public static void Main()
    {
        bool   b;
        double mst;
        Graph  g, t;

        Edge[] ep;
        var    rgg = new RandomGraphGenerator();
        var    ge  = new GraphExport();

        // nieskierowany - cykl
        rgg.SetSeed(1111);
        g = rgg.EulerGraph(typeof(AdjacencyMatrixGraph), false, 6, 1, 1, 4);
        b = g.Lab04_Euler(out ep);
        if (b)
        {
            Console.WriteLine("Znaleziono cykl Eulera w grafie 1 - ma {0} krawedzi", ep.Length);
            ge.Export(Construct(g.VerticesCount, ep));
        }
        else
        {
            Console.WriteLine("Nie znaleziono sciezki Eulera w grafie 1");
        }

        // skierowany - cykl
        rgg.SetSeed(2222);
        g = rgg.EulerGraph(typeof(AdjacencyMatrixGraph), true, 5, 1, 1, 3);
        b = g.Lab04_Euler(out ep);
        if (b)
        {
            Console.WriteLine("Znaleziono cykl Eulera w grafie 2 - ma {0} krawedzi", ep.Length);
            //ge.Export(Construct(g.VerticesCount, ep));
        }
        else
        {
            Console.WriteLine("Nie znaleziono sciezki Eulera w grafie 2");
        }

        // nieskierowany - sciezka
        rgg.SetSeed(3333);
        g = rgg.SemiEulerGraph(typeof(AdjacencyMatrixGraph), false, 6, 1, 1, 4);
        b = g.Lab04_Euler(out ep);
        if (b)
        {
            Console.WriteLine("Znaleziono sciezke Eulera w grafie 3 - ma {0} krawedzi", ep.Length);
            //ge.Export(Construct(g.VerticesCount, ep));
        }
        else
        {
            Console.WriteLine("Nie znaleziono sciezki Eulera w grafie 3");
        }

        // skierowany - sciezka
        rgg.SetSeed(4444);
        g = rgg.SemiEulerGraph(typeof(AdjacencyMatrixGraph), true, 5, 1, 1, 3);
        b = g.Lab04_Euler(out ep);
        if (b)
        {
            Console.WriteLine("Znaleziono sciezke Eulera w grafie 4 - ma {0} krawedzi", ep.Length);
            //ge.Export(Construct(g.VerticesCount, ep));
        }
        else
        {
            Console.WriteLine("Nie znaleziono sciezki Eulera w grafie 4");
        }

        // drzewo
        rgg.SetSeed(5555);
        g   = rgg.UndirectedGraph(typeof(AdjacencyMatrixGraph), 20, 0.5, -10, 50);
        mst = g.Lab04_Kruskal(out t);
        Console.WriteLine("Minimalne drzewo ma wage {0}", mst);
        //ge.Export(t);
    }
コード例 #27
0
ファイル: Muzeum.cs プロジェクト: MateuszChilinski/AiSD2
        /// <summary>
        /// Znajduje najliczniejszy multizbiór tras
        /// </summary>
        /// <returns>Znaleziony multizbiór</returns>
        /// <param name="g">Graf opisujący muzeum</param>
        /// <param name="cLevel">Tablica o długości równej liczbie wierzchołków w grafie -- poziomy ciekawości wystaw</param>
        /// <param name="entrances">Wejścia</param>
        /// <param name="exits">Wyjścia</param>
        public static MuseumRoutes FindRoutes(Graph g, int[] cLevel, int[] entrances, int[] exits)
        {
            Graph gC = g.Clone();
            Graph nG = new AdjacencyListsGraph <SimpleAdjacencyList>(true, g.VerticesCount * 2 + 2);// in - 0, out - g.V*2 + 1

            for (int i = 0; i < g.VerticesCount; i++)
            {
                nG.AddEdge(i + 1, i + g.VerticesCount + 1, cLevel[i]);
                foreach (Edge e in g.OutEdges(i))
                {
                    nG.AddEdge(e.From + 1, e.From + g.VerticesCount + 1, int.MaxValue);
                    nG.AddEdge(e.From + g.VerticesCount + 1, e.To + 1, int.MaxValue);
                }
            }
            foreach (var ent in entrances)
            {
                nG.AddEdge(0, ent + 1, cLevel[ent]);
            }
            foreach (var ext in exits)
            {
                nG.AddEdge(ext + 1, g.VerticesCount * 2 + 1, cLevel[ext]);
            }
            GraphExport gz = new GraphExport();
            //gz.Export(g);
            double z = nG.FordFulkersonDinicMaxFlow(0, g.VerticesCount * 2 + 1, out nG, MaxFlowGraphExtender.DFSBlockingFlow);


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

            for (int i = 0; i < nG.VerticesCount; i++)
            {
                foreach (var e in nG.OutEdges(i))
                {
                    if (e.Weight == 0)
                    {
                        nG.DelEdge(e);
                    }
                }
            }
            List <List <int> > tL = new List <List <int> >();

            for (int k = 0; k < z; k++)
            {
                getNext(ref nG, 0, ref tmp);
                tL.Add(tmp);
                tmp = new List <int>();
                for (int i = 0; i < nG.VerticesCount; i++)
                {
                    foreach (var e in nG.OutEdges(i))
                    {
                        if (e.Weight == 0)
                        {
                            nG.DelEdge(e);
                        }
                    }
                }
            }
            int[][] tA = new int[(int)z][];
            for (int i = 0; i < z; i++)
            {
                tA[i] = tL.ToArray()[i].ToArray();
            }
            return(new MuseumRoutes((int)z, tA));
        }