Пример #1
0
        static long roadsAndLibraries(int n, long c_lib, long c_road, int[][] cities)
        {
            GraphAPI gapi = new GraphAPI(n);

            for (int i = 0; i < cities.Length; i++)
            {
                gapi.AddEdge(cities[i][0], cities[i][1]);
            }

            ConnectedComponents bfs = new ConnectedComponents(gapi, n);
            long result             = ((c_road * bfs.RoadCount()) + (bfs.LibraryCount() * c_lib));

            if (c_lib * n < result)
            {
                result = c_lib * n;
            }

            return(result);
        }
Пример #2
0
        /*Suppose that we have n groups, of sizes a1 to an. Except when n is smallish, the following formula for the number N of ways
         * to choose a pair of people from different groups is more efficient:
         * N=((a1+⋯+an)^2 − (a1^2 +⋯+ an^2)) / 2.
         * To see that the formula does the job, expand (a1+⋯+an)2.*/
        static long journeyToMoon(int n, int[][] astronaut)
        {
            GraphAPI gapi = new GraphAPI(n);

            for (int i = 0; i < astronaut.Length; i++)
            {
                gapi.AddEdge(astronaut[i][0], astronaut[i][1]);
            }

            ConnectedComponents bfs     = new ConnectedComponents(gapi, n);
            IList <long>        IdCount = new List <long>();

            IdCount.Add(1);
            Array.Sort(bfs.Id);
            for (int k = 0; k < n - 1; k++)
            {
                if (bfs.Id[k] == bfs.Id[k + 1])
                {
                    ++IdCount[IdCount.Count - 1];
                    continue;
                }

                IdCount.Add(1);
            }

            long SumSquare = 0;

            for (int i = 0; i < IdCount.Count; i++)
            {
                SumSquare += IdCount[i];
            }

            SumSquare = (long)Math.Pow(SumSquare, 2);
            long SquareSum = 0;

            for (int i = 0; i < IdCount.Count; i++)
            {
                SquareSum += (long)Math.Pow(IdCount[i], 2);
            }

            return((SumSquare - SquareSum) / 2);
        }