Exemple #1
0
        void solve(int n, int m)
        {
            var binom = new BinomialCoefficient(n + m + 5);
            var dp    = new ModInt[n + 3, m + 3];

            dp[0, 0] = 1;
            for (int i = 0; i <= n; i++)
            {
                for (int j = 0; j <= m; j++)
                {
                    if (j > 0)
                    {
                        dp[i + 1, j] += j * dp[i, j];
                    }
                    dp[i, j + 1] += dp[i, j];
                }
            }
            ModInt ans = 0;

            for (int i = 0; i <= n; i++)
            {
                var v = dp[i, m];
                v   *= binom[n + m, i + m];
                v   *= binom.fact[n - i];
                ans += v;
            }
            ans *= binom.fact[m] * binom.fact[m];
            ans *= binom.fact[n];
            Console.WriteLine(ans);
        }
Exemple #2
0
    void solve()
    {
        int N = cin.nextint;
        var F = new ModInt[N + 1]; //??

        F[0] = 1;
        for (int i = 1; i <= N; i++)
        {
            F[i] = F[i - 1] * i;
        }

        var ncr = new BinomialCoefficient(N);

        var OMEGA = new ModInt[N]; //?????????

        for (int i = 1; i < N; i++)
        {
            OMEGA[i] = OMEGA[i - 1] + F[N - i - 1] * ncr[N, N - i - 1] * F[i];
            //WriteLine(" " + F[N - i - 1] * ncr[N, N - i - 1] + " " + OMEGA[i]);
        }
        var    A   = cin.scanlong;
        ModInt ans = 0;

        for (int i = 0; i < N; i++)
        {
            ans += F[N] * A[i];
            //WriteLine(i + " " + (OMEGA[N - i - 1] + OMEGA[i]));
            ans += OMEGA[N - i - 1] * A[i];
            ans += OMEGA[i] * A[i];
        }

        WriteLine(ans);
    }
Exemple #3
0
        public static void TeoremCalculateThrowsException(int n, int k)
        {
            // Arrange

            // Act

            // Assert
            _ = Assert.Throws <ArgumentException>(() => BinomialCoefficient.Calculate(n, k));
        }
Exemple #4
0
        public static void CalculateFromPairs(int n, int k, long expected)
        {
            // Arrange

            // Act
            var result = BinomialCoefficient.Calculate(n, k);

            // Assert
            Assert.AreEqual(expected, result);
        }
Exemple #5
0
    void solve()
    {
        int N   = cin.nextint;
        int K   = cin.nextint;
        var ncr = new BinomialCoefficient(N + K);

        if (K < N)
        {
            WriteLine(ncr[N + K - 1, K]);
        }
        else
        {
            WriteLine(ncr[N, K % N]);
        }
    }
Exemple #6
0
    void solve()
    {
        int N = cin.nextint;
        var G = new SortedDictionary <int, int>();

        for (int i = 0; i < N; i++)
        {
            int t = cin.nextint;
            if (G.ContainsKey(t))
            {
                G[t]++;
            }
            else
            {
                G[t] = 1;
            }
        }
        var    B    = new BinomialCoefficient(N);
        ModInt ans  = 1;
        long   sum  = 0;
        long   time = 0;

        foreach (var item in G)
        {
            for (int i = 0; i < item.Value; i++)
            {
                time += item.Key;
                sum  += time;
            }

            ans *= B.fact[item.Value];
        }

        WriteLine(sum);
        WriteLine(ans);
    }
Exemple #7
0
        public void Solve()
        {
            var n  = ri;
            var m  = ri;
            var sz = Enumerate(n, x => 1 << x);

            var all = sz.Sum();
            var dp  = new ModInt[1 << n];

            dp[0] = 1;
            var comb = new BinomialCoefficient(all + 50);

            foreach (var x in Enumerate(m, x => ri).OrderByDescending(x => x))
            {
                var next = new ModInt[1 << n];
                for (int i = 0; i < 1 << n; i++)
                {
                    var cnt = all - x + 2;
                    for (int j = 0; j < n; j++)
                    {
                        if ((i >> j & 1) == 1)
                        {
                            cnt -= sz[j];
                        }
                    }
                    next[i] += dp[i];
                    for (int j = 0; j < n; j++)
                    {
                        if ((i >> j & 1) == 1)
                        {
                            continue;
                        }
                        if (cnt < sz[j])
                        {
                            continue;
                        }
                        next[i | 1 << j] += dp[i] * comb[cnt - 1, sz[j] - 1] * comb.fact[sz[j]];
                    }
                }
                dp = next;
            }
            Debug.WriteLine(dp.AsJoinedString());
            ModInt ans = 0;

            for (int i = 0; i < 1 << n; i++)
            {
                var cnt = n;
                var rem = 0;
                for (int j = 0; j < n; j++)
                {
                    if ((i >> j & 1) == 0)
                    {
                        rem += sz[j]; cnt--;
                    }
                }
                dp[i] *= comb.fact[rem];
                Debug.WriteLine(dp[i]);
                ans += (cnt % 2 == 0) ? dp[i] : ModInt.Mod - dp[i].num;
            }
            ans *= ModInt.Pow(2, n);
            Console.WriteLine(ans);
        }
Exemple #8
0
 //Binomial Coefficient
 //Catalan value = C(2n, n)/n+1
 public static long GetNumberWithBinomialCoefficient(int n)
 {
     return(BinomialCoefficient.BinominalCoefficient(2 * n, n) / (n + 1));
 }
Exemple #9
0
        static void Main(string[] args)
        {
            // StringProblems
            //Test calls for Reverse string
            string input = "jacob";

            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));
            input = "jake";
            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));
            input = "";
            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));
            input = "jdshjdh@#$%^&)";
            Console.WriteLine(input + "<=>" + new string(SimpleProblem.ReverseString(input.ToCharArray())));

            ReplaceSpaces.TestReplaceSpacesInplace();
            Anagrams.TestIsAnagramAlgo();
            StringRotation.TestIsThisRotatedString();
            RemoveDuplicates.TestRemoveDuplicatesFromString();
            StringToLongConverter.TestStringToLong();
            RegexMatching.TestMatch();
            SumOfTwoNumbersInArray.TestSumOfTwoNumbersInArray();
            SumOfThreeNumbersInArray.TestSumOfThreeNumbersInArray();
            PairInSortedArrayClosestToAParticularValue.TestPairInSortedArrayClosestToAParticularValue();
            PalindromeInStringPermutation.TestPalindromeInStringPermutation();
            EditDistanceBetweenStrings.TestEditDistanceBetweenStrings();
            AnagramIsPalindrome.TestAnagramIsPalindrome();
            GreatestPalindrome.TestGreatestPalindrome();
            ReverseStringWithoutVowels.TestReverseStringWithoutVowels();
            LongestSubstringWithKDistinctChars.TestLongestSubstringWithKDistinctChars();
            // Pattern Matching
            NativePatternMatching.TestNativePatternMatching();
            KMPPatternMatching.TestKMPPatternMatching();
            BoyerMoorePatternMatching.TestPatternMatching();
            RabinKarp.TestRabinKarp();

            //Console.ReadLine();

            //Array Problems
            ArrayOfNumsIncrement.TestIncrementArrayOfNumbers();
            MajorityElement.TestFindMajorityElement();
            Merge2SortedArrays.TestMergeSortedArrays();
            MaxDistanceInArray.TestMaxDistanceInArray();
            MovingAverage.TestMovingAverage();
            TotalAverage.TestTotalAverage();
            ArrayWithGreaterElementToRight.TestArrayWithGreaterElementToRight();
            WaterCollectedInPuddleShownByHistogram.TestWaterCollectedInPuddleShownByHistogram();
            CountOfPairsWhichSumUpToGivenSum.TestCountOfPairsWhichSumUpToGivenSum();
            //Median.TestGetMedianOf2SortedArray();

            // Sorting Problems
            SelectionSort.TestSorting();
            BubbleSort.TestSorting();
            InsertionSort.TestSorting();
            ShellSort.TestSorting();
            MergeSort.TestMergeSort();
            QuickSort.TestQuickSort();
            HeapSortTester.TestHeapSort();
            CountingSort.TestSorting();
            RadixSort.TestRadixSort();
            DutchNationalFlag.TestDutchNationalFlag();
            SortedSquares.TestSortedSquares();

            // Matrix Problem
            Rotate_Matrix_90_degree.TestRotateMatrix();
            Matrix_Column_Rows_0.TestMakeRowColZero1();
            Matrix_Column_Rows_0.TestMakeRowColZero2();
            RotateMatrix180.TestRotateMatrix180();
            SumOfMatrixElementsFormedByRectangleWithCoordinates.TestSumOfMatrixElements();
            SortedArrayFromSortedMatrix.TestSortedArrayFromSortedMatrix();
            SearchWordInMatrix.TestSearchWordInMatrix();
            MaxOnesInRow.TestMaxOnesInRow();
            MatrixAsTriangle.TestMatrixAsTriangle();
            MinRangeInMatrix.TestMinRangeInMatrix();
            PrintMatrixAsSnake.TestPrintMatrixAsSnake();
            PrintMatrixInSpiral.TestPrintMatrixInSpiral();
            MaxSqAreaInBinaryMatrix.TestMaxRectAreaInBinaryMatrix();
            TicTacToeWinner.TestTicTacToeWinner();
            WaterfallCreation.TestWaterfallCreation();

            // Linked list Problems
            DeleteLinkedListNode.TestDeleteFirstNode();
            DeleteDuplicatesFromLinkedList.TestDeleteDuplicates();
            NthLastElementOfLinkedList.TestNthLastNodeOfLinkedList();
            DeleteNodeWithDirectReference.TestDeleteNode();
            AddNumbers.TestAddNumbersRepresentedByLinkedList();
            CopyLinkedListWithRandomNode.TestGetCopiedLinkedListWithRandomNode();
            CommonElementInTwoLinkedList.TestCommonElement();
            ReverseAdjacentNodesInLinkedList.TestReverseAdjacentNodes();
            MergeSortedLinkedList.TestMerge();
            CycleInLinkedList.TestStartOfCycleInLinkedList();
            MedianForCircularLinkedList.TestGetMedian();
            ReverseLinkedList.TestReverseLinkedList();
            SortedCircularLinkedList.TestCircularLinkedList();

            // stack and queue problem
            ThreeStackWithOneArray.TestThreeStackWithOneArray();
            StackWithMinElement.TestStackWithMinElement();
            StackOfPlates.TestStackOfPlates();
            SortAStack.TestSortAStackAscending();
            WellFormedExpression.TestWellFormedExpression();
            QueueVia2Stack.TestQueueVia2Stack();
            LRUCache.TestLRUCache();
            EvaluatePrefixNotation.TestGetPrefixNotationResult();
            EvaluateInflixNotation.TestGetInflixNotationResults();
            EvaluatePostfixNotation.TestGetPostfixNotationResult();
            TestCircularQueue.TestCircularQueueWithDifferentCases();
            LargestAreaInHistogram.TestLargestAreaInHistogram();
            TextEditerWithUndo.TestTextEditerWithUndo();

            //Recursion Problem
            TowerOfHanoi.TestTowerOfHanoi();
            MaxSumOfConsecutiveNums.TestMaxSumOfConsecutiveNums();

            // Back tracking problems
            Sudoku.TestSudokuSolver();
            HamiltonianCycle.TestHamiltonianCycle();
            GraphColoringWithMColors.TestGraphColoringWithMColors();
            MakeLargestIsland.TestMakeLargestIsland();

            //Misc Problem
            MinNumOfCoins.TestMinNumOfCoins();
            IsPrime.TestCheckPrime();
            SquareRoot.TestCalculateSquareRoot();
            CreditCardCheck.TestLuhnAlgo();
            ExcelFirstRowConversion.TestCovertExcelColumnToLong();
            Skyline.TestSkyline();
            SumOfSquaresWithoutMultiplication.TestSumOfSquares();
            MergeIntervals.TestMergeIntervals();
            WidthOfCalendar.TestWidthOfCalendar();
            JosephusProblem.TestJosephusProblem();

            // Permutation and Combination problem
            ShuffleAList.TestFisherYatesAlgo();
            CombinationsOfBinaryString.TestCombinationsOfBinaryString();
            AllCombinationsOfString.TestAllCombinationsOfString();
            AllPermutationsOfString.TestAllPermutationsOfString();
            PhoneNumberToWords.TestPhoneNumberToWords();
            AllNumbersInRangeWithDifferentDigits.TestAllNumbersInRangeWithDifferentDigits();
            DivideSetIntoTwoEqualSetsWithMinSumDiff.TestDivideSetIntoTwoEqualSetsWithMinSumDiff();
            PowerSet.TestPowerSet();
            AllCombinationsOfParenthesis.TestAllCombinationsOfParenthesis();
            GoodDiceRoll.TestGoodDiceRoll();
            PermutationsOfValidTime.TestPermutationsOfValidTime();

            // Tree Problems
            TreeFromExpression.TestCreateTreeFromExpression();
            TestBinarySearchTree.TestDifferentOperationsOnBST();
            AncestorOfTwoNodesInBST.TestAncestorOfTwoNodesInBST();
            CheckBTisBST.TestCheckBTisBST();
            MaxSumOnTreeBranch.TestMaxSum();
            WalkTheTree.TestWalkTheTree();
            SkewedBSTToCompleteBST.TestConvertSkewedBSTToCompleteBST();
            CheckIfTheTreeIsBalanced.TestIsTreeBalanced();
            LinkedListOfTreeNodesAtEachDepth.TestCreateLinkedListOfTreeNodesAtEachDepth();
            PrintBinaryTreeNodeAtEachLevel.TestPrintBinaryTreeNodeAtEachLevel();
            PrintBinaryTreeNodeAtEachLevelSpirally.TestPrintBinaryTreeNodeAtEachLevelSpirally();
            TreeSubtreeOfAnother.TestMatchTree();
            AncestorOfTwoNodesInBT.TestGetAncestorOfTwoNodesInBT();
            AncestorOfMultiNodesInBT.TestAncestorOfMultiNodesInBT();
            LinkedListFromLeavesOfBT.TestLinkedListFromLeavesOfBT();
            ExteriorOfBT.TestPrintExteriorOfBT();
            DepthOfTree.TestGetDepthOfTree();
            TreeToColumns.TestTreeToColumns();
            KthSmallestElementFromBST.TestKthSmallestElementFromBST();
            MakeBSTFromPreOrder.TestMakeBSTFromPreOrder();
            MirrorATree.TestMirrorATree();
            CloneABTWithRandPointer.TestCloneABTWithRandPointer();
            TreeWithInorderAndPreorder.TestTreeWithInorderAndPreorder();
            TreeWithInorderAndPostorder.TestTreeWithInorderAndPostorder();
            TreePathSumsToValue.TestTreePathSumsToValue();
            AllPathInNArayTree.TestAllPathInNArayTree();
            SerializeDeserializeBinaryTree.TestSerializeDeserializeBinaryTree();
            SerializeDeserializeAnNaryTree.TestSerializeDeserializeAnNaryTree();
            AncestorOfTwoNodesInNaryTree.TestAncestorOfTwoNodesInNaryTree();
            AbsOfMaxAndSecondMaxDepthInBT.TestGetAbsOfMaxAndSecondMaxDepthInBT();

            // Trie problems
            CreateAndSearchSimpleTrie.TestCreateAndSearchSimpleTrie();
            // ToDo: have a problem of suffix trees
            ShortestPrefix.TestGetShortestPrefixNotPresentInStringSet();

            // Dynamic Programming problems
            LongestCommonSubsequence.TestGetLongestCommonSubsequence();
            LongestPalindromeSubString.TestGetLongestPalindromeSubString();
            LongestPalindromicSubsequence.TestGetLongestPalindromicSubsequence();
            MaximumAs.TestGetMaximumAs();
            MinNumberOfJumps.TestGetMinimumNumberOfJumps();
            LongestCommonSubString.TestGetLongestCommonSubString();
            KnapSackProblem.TestGetTheMaximumValueWithLimitedWeight();
            TreeCuttingProblem.TestGetTreeCuttingToMaximizeProfits();
            WordBreaking.TestBreakTheWords();
            DistanceOfWords.TestDistanceOfWords();
            LongestIncreasingSubSequence.TestLongestIncreasingSubSequence();
            MinCostPath.TestMinCostPath();
            DifferentWaysForCoinChange.TestDifferentWaysForCoinChange();
            MatrixMultiplication.TestMatrixMultiplication();
            BinomialCoefficient.TestBinomialCoefficient();
            BoxStacking.TestBoxStacking();
            WordWrapping.TestWordWrapping();
            MaxSubMatrixWithAllOnes.TestMaxSubMatrixWithAllOnes();
            LongestSubStringWithEqualSum.TestLongestSubStringWithEqualSum();
            PartitionArrayIntoEqualSumSets.TestPartitionArrayIntoEqualSumSets();
            MaxSumRectangle.TestMaxSumRectangle();
            RegularExpressionMatch.TestRegularExpressionMatch();
            NumRepresentedByPerfectSquares.TestNumRepresentedByPerfectSquares();
            LongestCommonSubsequenceInSameString.TestLongestCommonSubsequenceInSameString();
            StringDecodeAsAlphabets.TestStringDecodeAsAlphabets();
            BalloonBursting.TestBalloonBursting();
            TravellingSalesmanProblem.TestTravellingSalesmanProblem();
            MaxSumWithoutAdjacentElements.TestMaxSumWithoutAdjacentElements();
            MaxPathThroughMatrix.TestMaxPathThroughMatrix();
            BrickLaying.TestBrickLaying();
            JobSchedullingWithConstraints.TestJobSchedullingWithConstraints();
            EggDropMinTrials.TestEggDropMinTrials();

            // Graph Problems
            ShortestPath.TestGetShortestPathBetween2Vertex();
            CycleInDirectedGraph.TestIsCycleInDirectedGraph();
            CycleInUnDirectedGraph.TestIsCycleInUnDirectedGraph();
            SolveAMaze.TestSolveAMaze();
            AllPathsGivenStartEndVertex.TestGetAllPathsInGraphFromStartVertexToEndVertex();
            AllPaths.TestGetAllPathsInGraphFromStartVertex();
            ColorVertices.TestColorVerticesWithDifferentColor();
            CheckBipartiteGraph.TestCheckBipartiteGraph();
            TransformOneWordToAnother.TestGetTransformation();
            ConstraintsVerification.TestConstraintsVerification();
            ExtendedContactsInSocialNetwork.TestComputeExtendedContacts();
            CourseScheduling.TestCourseScheduling();
            SnakeAndLadder.TestSnakeAndLadder();
            IsGraphATree.TestIsGraphATree();
            ReverseGraph.TestReverseGraph();
            StronglyConnectedGraph.TestStronglyConnectedGraph();
            ConnectedComponents.TestConnectedComponents();
            ContinentalDivide.TestContinentalDivide();
            CloneGraph.TestCloneGraph();
            Wordament.TestWordament();
            // ShortestPathAlgo
            FloydWarshall.TestFloydWarshall();
            DijkstraAlgorithm.TestDijkstraAlgorithm();
            BellmanFord.TestBellmanFord();
            TravelFromLeftToRightInMatrix.TestTravelFromLeftToRightInMatrix();
            HeuristicSearch.TestHeuristicSearch();
            AStar.TestAStar();
            ShortestPathWhenObstaclesRemoved.TestShortestPathWhenObstaclesRemoved();
            ShortestDistanceFromRoomsToGates.TestShortestDistanceFromRoomsToGates();
            //MaxFlow
            FordFulkersonEdmondKarp.TestFordFulkersonEdmondKarp();
            MinCut.TestMinCut();
            MaximumBipartiteMatching.TestMaximumBipartiteMatching();
            //Minimum Spanning Tree
            KruskalAlgorithm.TestKruskalAlgorithm();
            PrimsAlgorithm.TestPrimsAlgorithm();


            //Heap problems
            BasicMaxHeap.TestMaxHeap();
            BasicMinHeap.TestMinHeap();
            TestMinHeapMap.DoTest();
            TestPriorityQueue.Run();
            MedianForAStreamOfNumbers.TestMedianForAStreamOfNumbers();

            //DisjointSets
            TestingDisjointSet.Run();
            //TestWeightedDisjointSetsWithPathCompression.Run(); // this runs slow, hence commenting it

            //Geometry
            ClosestPairOfPoints.TestClosestPairOfPoints();
            RectangleIntersection.TestRectangleIntersection();
            LineSegmentIntersection.TestLineSegmentIntersection();
            ConvexHull.TestConvexHull();
            KClosestPointToOrigin.TestKClosestPointToOrigin();

            //Greedy Algorithm
            HuffmanCoding.TestHuffmanCoding();

            //Randomized Algorithm
            RandomGeneration.TestRandomGeneration();

            // Bit Algorithms
            IntHaveOppositeSigns.TestIntHaveOppositeSigns();
            Parity.TestParity();

            //Math Problem
            ZerosInFactorial.TestZerosInFactorial();
            GetAllPrimeFactors.TestGetAllPrimeFactors();
            NumberOfFactors.TestNumberOfFactors();
            AllFactors.TestAllFactors();
            MultiplyLongNumbers.TestMultiplyLongNumbers();
            NextLargestPermutation.TestNextLargestPermutation();
            AllPrimesTillN.TestAllPrimesTillN();
            PascalsTriangle.TestPascalsTriangle();
            SubtractLongNumbers.TestSubtractLongNumbers();

            //Search problems
            SearchInSortedRotatedArray.TestSearchInSortedRotatedArray();
            KClosestElementInArray.TestKClosestElementInArray();
            SearchInSortedMatrix.TestSearchInSortedMatrix();
            BinarySearchUnbounded.TestBinarySearchUnbounded();
            LinkedListSublistSearch.TestLinkedListSublistSearch();
            NoOfOccuranceInSortedArray.TestNoOfOccuranceInSortedArray();
            GetSmallestInSortedRotatedArray.TestGetSmallestInSortedRotatedArray();

            //Distributed algorithms
            KWayMerge.TestKWayMerge();


            Console.ReadLine();
        }
Exemple #10
0
        private float basisFunction(int i, float time)
        {
            int n = model.ControlPoints.Count - 1;

            return(BinomialCoefficient.С(n, i) * Mathf.Pow(time, i) * Mathf.Pow(1 - time, n - i));
        }