├── .gitignore ├── README.md ├── code-c ├── capple.c ├── chefbr.c ├── dis.c ├── enor.c ├── life.c ├── lup.c ├── sanskar.c ├── strrep.c ├── sum_area.c └── trail.c ├── code-cpp ├── 2DmatrixSum.cpp ├── EXGCD.cpp ├── abPairedge.cpp ├── abcdef.cpp ├── abroads.cpp ├── absoluteDiffGeqLimit.cpp ├── addOpFraction.cpp ├── akashGCD.cpp ├── alternate+-.cpp ├── amaexper.cpp ├── amifib.cpp ├── anagramIndicesInString.cpp ├── arraySplit.cpp ├── atm.cpp ├── attrParse.cpp ├── avlTree.cpp ├── bSheep.cpp ├── balParen.cpp ├── basicCalculator.cpp ├── basicCalculatorII.cpp ├── bdayConstr.cpp ├── bearLeader.cpp ├── beatlesLCM.cpp ├── beautStrings.cpp ├── bennyQuery.cpp ├── bestStockBuySellCooldown.cpp ├── bibonacci.cpp ├── bigQueriesLazy.cpp ├── bikeRace.cpp ├── binTreeQ.cpp ├── binaryTreeFromString.cpp ├── binary_heap.cpp ├── bitsstdc++.h ├── blackShapes.cpp ├── booTravels.cpp ├── bstMaxPathSum.cpp ├── candyRam.cpp ├── captureBoardReg.cpp ├── catalan.cpp ├── cballs.cpp ├── centroidDecomp.cpp ├── chSegments.cpp ├── checkIfGoodArray.cpp ├── chefSqArr.cpp ├── chefTet.cpp ├── chefWorries.cpp ├── chefque.cpp ├── chefston.cpp ├── chrisDivisors.cpp ├── chrisGifts.cpp ├── chrisQueries.cpp ├── chrisStr.cpp ├── chrisTree.cpp ├── chrisTreeEff.cpp ├── closedPair.cpp ├── closestLeaf.cpp ├── cnote.cpp ├── coderGf.cpp ├── colTree.cpp ├── colorfulNo.cpp ├── combBack.cpp ├── confusingNumberII.cpp ├── contactsTrie.cpp ├── cookSched.cpp ├── coolGuy.cpp ├── copyRandomList.cpp ├── correctBinaryTree.cpp ├── countAp.cpp ├── countByte.cpp ├── countDivisors.cpp ├── countingSort.cpp ├── courseSchedule.cpp ├── crackingSafe.cpp ├── cseq.cpp ├── dagQueries.cpp ├── decodeWays.cpp ├── deepCopy.cpp ├── deepestLeavesLCA.cpp ├── dependency.cpp ├── devGostr.cpp ├── diStringMatch.cpp ├── dijkstraShort.cpp ├── distSubSeq.cpp ├── distinctWin.cpp ├── divB266.cpp ├── divMac.cpp ├── divSum.cpp ├── doublyLink.cpp ├── evalRPN.cpp ├── expressiveWords ├── expressiveWords.cpp ├── fact.cpp ├── factLenSum.cpp ├── fanQuot.cpp ├── fatland.cpp ├── fdivgame.cpp ├── fenwick_tree.cpp ├── fibDP.cpp ├── fibQueries.cpp ├── findMisDup.cpp ├── findRepeatedDuplicate.cpp ├── fireCity.cpp ├── firstMissingPositive.cpp ├── fixedPoint.cpp ├── flattenTreeToList.cpp ├── flipOne.cpp ├── fourCQuery.cpp ├── frieMeetLCA.cpp ├── friemeet.cpp ├── frjump.cpp ├── frmq.cpp ├── game-of-codes.cpp ├── gameWinnerK.cpp ├── gcdCNPrime.cpp ├── gcdPowerFour.cpp ├── gcdq.cpp ├── generateParen.cpp ├── geoCheat.cpp ├── giftChef.cpp ├── girderFlash.cpp ├── goodSeq.cpp ├── goodStrings.cpp ├── graphSever.cpp ├── graphTrav.cpp ├── gridWalk.cpp ├── guessNumber.cpp ├── guessNumberII.cpp ├── heapSort.cpp ├── holes.cpp ├── horrible.cpp ├── horribleRSQ.cpp ├── hotel.cpp ├── indexedPrior.cpp ├── informManagerTree.cpp ├── inorderSuccessorBST.cpp ├── inorderSuccessorBSTParent.cpp ├── inorderTraversalIterative.cpp ├── integerToEnglishWords.cpp ├── isPowerOfFour.cpp ├── ishanTick.cpp ├── justifiedText.cpp ├── k-good.cpp ├── kamahaha.cpp ├── kirkMemeLand.cpp ├── kirlab.cpp ├── kirlabBrute.cpp ├── kmpPatternMatch.cpp ├── knightsChess.cpp ├── kthAncestor.cpp ├── kthLargestElement.cpp ├── kthPerm.cpp ├── larg_rect.cpp ├── largestRect.cpp ├── lcaConstant.cpp ├── lcpTrie.cpp ├── lcsPrint.cpp ├── leastListIndexSum.cpp ├── leavesOfBinaryTree.cpp ├── levelOrder.cpp ├── linear_sort.cpp ├── lisSpoj.cpp ├── lockSeq.cpp ├── longMult.cpp ├── longestCommonPrefix.cpp ├── longestConsecutivePathTree.cpp ├── longestHappyPrefix.cpp ├── longestIncreasingPath.cpp ├── longestPalin.cpp ├── longestPalindromicSubstring.cpp ├── longestPrefix.cpp ├── longestSubstrWithAtmostKDistinct.cpp ├── longestSubstrWithoutRepChar.cpp ├── lostCampers.cpp ├── lovelyCouple.cpp ├── lowUpper.cpp ├── lowestCommonAncestor.cpp ├── lowestCommonAncestorBst.cpp ├── lowestCommonAncestorMultiple.cpp ├── lowestCommonAncestorWithParent.cpp ├── mandy_swag.cpp ├── marshPeri.cpp ├── matrixWithNearestZeroDist.cpp ├── maxEdgeConnected.cpp ├── maxElemStack.cpp ├── maxGap.cpp ├── maxMinXor.cpp ├── maxProductSubArray.cpp ├── maxProfitInJobScheduling.cpp ├── max_points_line.cpp ├── max_subarr.cpp ├── maxset.cpp ├── maxsubmod.cpp ├── median-datastream.cpp ├── medianTree.cpp ├── mergeKSortedLists.cpp ├── mergeLink.cpp ├── mergeSort.cpp ├── mergeSorted.cpp ├── microFact.cpp ├── minEdits.cpp ├── minHeightTree.cpp ├── minInsertions.cpp ├── minOperations.cpp ├── minPenalty.cpp ├── minRemoveToMakeValid.cpp ├── minSwapsMonotonic.cpp ├── minWindowSubsequence.cpp ├── minWindowSubstring.cpp ├── min_pal.cpp ├── missingPos.cpp ├── mkthNumSegVec.cpp ├── moAlgo.cpp ├── mod_sieve.cpp ├── monkLargestGraph.cpp ├── monkXorTree.cpp ├── mysteriousFunc.cpp ├── nextGreaterElemI ├── nextGreaterElemI.cpp ├── nextGreaterElemII.cpp ├── nextGreaterElemIII.cpp ├── nextPerm.cpp ├── next_perm.cpp ├── ninjaSet.cpp ├── noPrefixSet.cpp ├── nonAdjacent.cpp ├── nondec.cpp ├── numPalindromicSubstring.cpp ├── numberOfProvinces.cpp ├── oddDiv.cpp ├── orderHeights.cpp ├── palinResbit.cpp ├── palin_tree.cpp ├── patternOverlap.cpp ├── perShifts.cpp ├── perfectBinTree.cpp ├── perfectSquares.cpp ├── pishtyNim.cpp ├── playNumbers.cpp ├── poisonPlant.cpp ├── polyEval.cpp ├── popTree.cpp ├── powerSet.cpp ├── powsums.cpp ├── presidentGala.cpp ├── primeCouple.cpp ├── probPalin.cpp ├── productArrayExceptSelf.cpp ├── qHeap.cpp ├── quadTree.cpp ├── quickSelect.cpp ├── quickSort.cpp ├── rankPred.cpp ├── rectIntersect.cpp ├── redJohn.cpp ├── redundantConnections.cpp ├── redundantConnectionsII.cpp ├── removeKDigits.cpp ├── removeStones.cpp ├── reorderSpaces.cpp ├── reverseEdge.cpp ├── reverseString.cpp ├── riddleV2.cpp ├── rmq.cpp ├── robotsInCircle.cpp ├── rootMinHeap.cpp ├── roseAlexey.cpp ├── rotation.cpp ├── roundNumbit.cpp ├── sabaGrid.cpp ├── save_nat.cpp ├── searchRotatedSortedArray.cpp ├── seastone.cpp ├── sebiTel.cpp ├── segAshu.cpp ├── segDominant.cpp ├── segment2d.cpp ├── segmentHoneyIshu.cpp ├── segmentMap.cpp ├── segmentOpen.cpp ├── segmentRoyCoin.cpp ├── segmentTree.cpp ├── segment_lazy.cpp ├── segment_sieve.cpp ├── segment_tree_sum.cpp ├── seqXY.cpp ├── serejaWays.cpp ├── setdiff.cpp ├── shiniApples.cpp ├── shortestBFS.cpp ├── shortestPathAllKeys.cpp ├── sieveEros.cpp ├── simPair.cpp ├── simpleTextEd.cpp ├── slides.cpp ├── slidingWindowMax.cpp ├── slidingWindowMin.cpp ├── snackMaxSum.cpp ├── sortLinkedList.cpp ├── sortedToBst.cpp ├── sparseRMQ2d.cpp ├── sparseTable.cpp ├── spartaWar.cpp ├── spiralOrder.cpp ├── spojCot.cpp ├── steadyGene.cpp ├── stoneDiv.cpp ├── strRed.cpp ├── string-func.cpp ├── subArrayWithKDiffIntegers.cpp ├── subMatricesCount.cpp ├── subarray-sum-eq-k.cpp ├── subsetSumBalanced.cpp ├── subtreeRemoval.cpp ├── suffix_arr.cpp ├── sumDistancesInTree.cpp ├── sumFibNum.cpp ├── sumdis.cpp ├── summingUp.cpp ├── surroundedRegions.cpp ├── taskSched.cpp ├── ternarySearch.cpp ├── test.cpp ├── threeSum.cpp ├── totient_eff.cpp ├── trappingRainWater.cpp ├── treap.cpp ├── treeDiameter.cpp ├── treeOps.cpp ├── tree_diff.cpp ├── trie.cpp ├── trieMake.cpp ├── trustNet.cpp ├── twoRobots.cpp ├── twoThreeflip.cpp ├── uniqueBSTSum.cpp ├── uniquePaths.cpp ├── validPlus.cpp ├── varArrays.cpp ├── vbKhelu.cpp ├── vertex_cover.cpp ├── verticalOrderTraversal.cpp ├── verticalOrderTraversalOfTree.cpp ├── waiterStack.cpp ├── waveSeq.cpp ├── waysDijkstra.cpp ├── waysPlanarRoad.cpp ├── wordLadder.cpp ├── wordSearch.cpp ├── workchef.cpp ├── xennyClass.cpp ├── xorQ.cpp ├── xorsubv.cpp └── zanSmart.cpp ├── code-go ├── add_two_numbers.go ├── can_permutate.go ├── go.mod ├── go.sum ├── group_anagrams.go ├── in_memory_file_system.go ├── integer_to_english_words.go ├── integer_to_roman.go ├── lfu_cache.go ├── linked_list.go ├── lru_cache.go ├── median_of_sorted_arrays.go ├── min_job_schedule_difficulty.go ├── next_greater_element.go ├── number_islands.go ├── reverseInteger.go ├── roman_to_integer.go ├── struct_cmp.go ├── tictactoe │ ├── tictactoe.go │ └── tictactoe_test.go ├── uuid_random.go ├── valid_anagram.go └── zigzagConversion.go ├── code-hs ├── countExperts.hs ├── customOrd.hs ├── devArr.hs ├── input_arr.hs ├── ishanStrings.hs ├── life.hs ├── maxmin.hs ├── morningAssem.hs ├── ndiffpal.hs ├── palinSubstr.hs ├── tricoin.hs └── xentask.hs ├── code-java ├── pom.xml └── src │ └── main │ └── java │ ├── AlbumsCost.java │ ├── Bitset.java │ ├── CardGame.java │ ├── ChainAlpha.java │ ├── CompositeNum.java │ ├── DoubleCheckedLocking.java │ ├── EqualChoc.java │ ├── LRUCache.java │ ├── LcsPrint.java │ ├── LoggerRateLimiter.java │ ├── PeekingIterator.java │ ├── PhoneDirectory.java │ ├── PowerBase.java │ ├── PresidentialVoting.java │ ├── ProdSquare.java │ ├── RateLimiter.java │ ├── RemoveStones.java │ ├── TicTacToe.java │ ├── TicTacToeBitset.java │ ├── TicTacToeBitsetNoSpace.java │ ├── WorkExecutor.java │ ├── milyPen.java │ └── palindTime.java ├── code-js ├── cookSched.js └── hello.js ├── code-py ├── 2darray.py ├── 4sum.py ├── absPerm.py ├── allParentPairs.py ├── allocarry.py ├── almostPal.py ├── alost.py ├── anagram.py ├── annualParty.py ├── antiDiagonals.py ├── appendDel.py ├── apuInit.py ├── arrRot.py ├── arrays.py ├── ashigift.py ├── ashu_prime.py ├── astring.py ├── avlTree.py ├── babySteps.py ├── backToorig.py ├── bagapple.py ├── balStrLen.py ├── ballElim.py ├── bandMatr.py ├── base_one.py ├── basicStat.py ├── bearVow.py ├── beautArray.py ├── beautPairs.py ├── beautQuad.py ├── bennyBall.py ├── bennyGifts.py ├── bennySegments.py ├── bennyTriag.py ├── betweenSet.py ├── bigQueriesLazy.py ├── biggerAsc.py ├── binSqModsum.py ├── binarystring.py ├── binops.py ├── boo.py ├── botsChal.py ├── brokphon.py ├── bruteReg.py ├── bwcell.py ├── candyReplenish.py ├── carlos.py ├── carlsenChess.py ├── chaos.py ├── chchain.py ├── chcube.py ├── chearmy.py ├── chefColor.py ├── chefDish.py ├── chefElec.py ├── chefKey.py ├── chefTriples.py ├── chefWorry.py ├── chef_cake.py ├── chef_lcs.py ├── chefanup.py ├── chefarc.py ├── chefark.py ├── chefaxr.py ├── chefdtre.py ├── cheflcm.py ├── chefrp.py ├── chefstlt.py ├── chequ.py ├── chessLove.py ├── chrisDig.py ├── chrisDish.py ├── chrisDiv.py ├── chrisPerm.py ├── chrisStr.py ├── chstamp.py ├── chuckBin.py ├── claimTrue.py ├── closestStr.py ├── closingCer.py ├── clperm.py ├── cnote.py ├── codeRed.py ├── combBack.py ├── combSum.py ├── cookmach.py ├── countAp.py ├── countLuck.py ├── count_strings.py ├── coverIntAPAC.py ├── cperm.py ├── cseq.py ├── dayaLock.py ├── dbCrush.py ├── dcgame.py ├── defribil.py ├── dekisugi.py ├── designer-mat.py ├── destMonster.py ├── destroy.py ├── devArr.py ├── devstr.py ├── dfsBasic.py ├── diffOfK.py ├── distInPath.py ├── dist_codes.py ├── dist_node.py ├── distinctMat.py ├── divB339.py ├── divMac2.py ├── divMaxSum.py ├── divProb.py ├── divSpan.py ├── divb467.py ├── divbyEightperm.py ├── dividors_py3.py ├── divmac.py ├── driverSight.py ├── edgeDiscycle.py ├── egbobrt.py ├── elementalOrb.py ├── emitl.py ├── emma.py ├── equality.py ├── eulerTour.py ├── exception.py ├── exnetwk.py ├── expalin.py ├── extran.py ├── factLenSum.py ├── factorial.py ├── fairRation.py ├── fast_squarer.py ├── fatalGroup.py ├── fenwickIter.py ├── ffcomb.py ├── fibLastNdig.py ├── fibMatrix.py ├── find-angle.py ├── find_exp.py ├── find_max.py ├── fiveMul.py ├── fractalArt.py ├── fractal_tree.py ├── fractionStr.py ├── freidoNum.py ├── frjump.py ├── frmq.py ├── fruitShop.py ├── fruitsExc.py ├── gameofdrinks.py ├── gasStation.py ├── gcdq.py ├── geoCheat.py ├── giftchef.py ├── goodString.py ├── goodStringsAB.py ├── goodSubSeq.py ├── goodlandElec.py ├── grayCode.py ├── grguy.py ├── gridGreedy.py ├── hashEqual.py ├── heapsort.py ├── hex-color.py ├── hibina.py ├── html-tags.py ├── htmlLuna.py ├── increasingSub.py ├── insomnia.py ├── interBit.py ├── intersect.py ├── isRmqSeg.py ├── jamCoins.py ├── jpStrings.py ├── just_mult.py ├── kfunc.py ├── kitchenTT.py ├── kthFractionNthStep.py ├── kthSmall.py ├── kthmax.py ├── ladiaKush.py ├── lampPost.py ├── larg.py ├── largeContZero.py ├── largestBou.py ├── largestTimeForDigits.py ├── lastWord.py ├── lcmFast.py ├── lcs.py ├── lead.py ├── learniter.py ├── letterPhone.py ├── lfive.py ├── lisaWork.py ├── lockSeq.py ├── logExclusiveTime.py ├── longPalinSeq.py ├── longSubRep.py ├── longSum.py ├── longestSeq.py ├── lucasCRT.py ├── luckyNum.py ├── mahasena.py ├── makeArrayEq.py ├── makeLongPalin.py ├── makelis.py ├── mandraDp.py ├── matXor.py ├── mat_rotate.py ├── mathProb.py ├── maxCircle.py ├── maxKSum.py ├── maxSumPath.py ├── maxiSum.py ├── maximalSub.py ├── maximize-it.py ├── maxremSum.py ├── maxxor.py ├── mediumSumSubset.py ├── megaTic.py ├── merge-tools.py ├── mergeIntervals.py ├── mergeSorted.py ├── merge_inv.py ├── metroRide.py ├── microSpot.py ├── millyTest.py ├── mimeType.py ├── minCabService.py ├── minCuts.py ├── minJumpCost.py ├── minMaxscores.py ├── minScoretriangulation.py ├── minStack.py ├── minions.py ├── mod_sieve.py ├── monkHeight.py ├── monkInteger.py ├── monkMod.py ├── monkMountain.py ├── monkSwaptree.py ├── monkTreeBST.py ├── monkWalk.py ├── most-commons.py ├── most-distant.py ├── movieWeek.py ├── nQueens.py ├── niceSeq.py ├── ninjaArray.py ├── nobitaSeq.py ├── nonOverlappingIntervals.py ├── nonPrimePairs.py ├── onek.py ├── orderChairPerson.py ├── p3.py ├── paintbox.py ├── palSubstr.py ├── pal_anagram.py ├── palinPart.py ├── palinSubstr.py ├── palindromicDates.py ├── palinsSubseq.py ├── palsub.py ├── pancakeMan.py ├── patheticRichard.py ├── patternsOverlap.py ├── peaks.py ├── perShifts.py ├── piano.py ├── piece_cake.py ├── pishtyNim.py ├── pmark.py ├── pointsLine.py ├── pokeDiv.py ├── pokedentity.py ├── popcount.py ├── popsicMount.py ├── powerSet.py ├── powerplants.py ├── powsums.py ├── pratFrie.py ├── prefixNum.py ├── pretty_time.py ├── primitiveRoot.py ├── progressPie.py ├── proportion.py ├── pyt_parse.py ├── qmatrix.py ├── qset.py ├── quantum_land.py ├── queriesDig.py ├── quickSelect.py ├── rainWater.py ├── rajSim.py ├── rankAndFile.py ├── ranklist.py ├── redundantBrace.py ├── regex_group.py ├── regex_matching.py ├── repeatedSubstrPattern.py ├── rescalc.py ├── restoreIp.py ├── reverse_shufle.py ├── riskTrade.py ├── romanNum.py ├── samu_cards.py ├── savingSearch.py ├── scalarProd.py ├── seaarasu.py ├── sealine.py ├── search2D.py ├── seats.py ├── senateEvac.py ├── seqlcs.py ├── serejaIncr.py ├── serejaProg.py ├── setZero.py ├── setdiff.py ├── sevenSegment.py ├── shamuHelp.py ├── shareCand.py ├── sherParen.py ├── sherlockHelp.py ├── sherlock_beast.py ├── shilXor.py ├── sieve_eros.py ├── simStrings.py ├── simpPath.py ├── simpleOne.py ├── simplePalin.py ├── simple_sum.py ├── sort_dec.py ├── sortrow.py ├── specialCoprime.py ├── spiralMsg.py ├── spiralSquare.py ├── squareChef.py ├── squareCount.py ├── square_subset.py ├── stackPiingUp.py ├── stfm.py ├── stockMax.py ├── strConv.py ├── straightQues.py ├── straight_flush.py ├── stringDp.py ├── strq.py ├── subArrayProd.py ├── sub_in_matrix.py ├── submaskQuery.py ├── subsets.py ├── substrConcat.py ├── sudoku.py ├── sumPieces.py ├── sum_is_mul.py ├── superValid.py ├── swap-case.py ├── talazy.py ├── taskSched.py ├── tdriver.py ├── testSum.py ├── testgen.py ├── threeSumZero.py ├── timeAsr.py ├── totient_eff.py ├── trainPartner.py ├── transformAB.py ├── triangleClass.py ├── tricoin.py ├── twoChar.py ├── twoSumHash.py ├── twostr.py ├── userTransactions.py ├── vCake.py ├── vanMohatsav.py ├── vanyaNum.py ├── vbKhelu.py ├── vcs.py ├── vibhuPair.py ├── votersToWin.py ├── warehouse.py ├── watsum.py ├── wayout.py ├── windowStr.py ├── wordCount.py ├── xentask.py ├── xornum.py ├── xorsub.py └── xrqrs.py └── code-rb ├── chef_cake.rb └── kfunc.rb /.gitignore: -------------------------------------------------------------------------------- 1 | *.dSYM 2 | a.out 3 | .vscode* 4 | .idea* 5 | .DS_Store 6 | cmake* 7 | Makefile * 8 | code-java/out 9 | code-java/*.iml 10 | code-java/target 11 | code-cpp/README.md 12 | code-go/README.md 13 | Testing 14 | Makefile 15 | *.cbp 16 | bin/ 17 | -------------------------------------------------------------------------------- /code-c/capple.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int test,n,apple,i; 6 | scanf("%d",&test); 7 | 8 | while(test--) 9 | { 10 | int arr[100010]={0}; 11 | int count=0; 12 | 13 | scanf("%d",&n); 14 | for(i=0; i 2 | #include 3 | 4 | //to detect maximum distinguishable distinct sub string ina given string and give its count 5 | 6 | int main() 7 | { 8 | printf("HI hi\n"); 9 | int t,i,k; int count=0,flag=0; 10 | char a[10],b[10]; 11 | 12 | scanf("%d",&t); 13 | 14 | while(t<=10 && t>=1) 15 | { 16 | scanf("%s",a); 17 | strcpy(b,a); 18 | 19 | for(i=0; i 2 | #include 3 | #define mod 1000000009 4 | 5 | int* performOps(int *A, int len, int *blen) { 6 | int i; 7 | *blen = len * 2; 8 | int *B = (int *)malloc((*blen) * sizeof(int)); 9 | for (i = 0; i < len; i++) { 10 | B[i] = A[i]; 11 | B[i + len] = A[(len - i) % len]; 12 | } 13 | return B; 14 | } 15 | 16 | 17 | int main() 18 | { 19 | int blen; 20 | int A[] = {5,10,2,1}; 21 | int *B = performOps(A, 4, &blen); 22 | int i; 23 | for (i = 0; i < blen; i++) { 24 | printf("%d ", B[i]); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /code-c/life.c: -------------------------------------------------------------------------------- 1 | #include //minimum trip distance 2 | #define mod 1000000009 3 | 4 | 5 | int main() 6 | { 7 | int a; 8 | 9 | scanf("%2d",&a); 10 | 11 | while(a!=42) 12 | { 13 | printf("%d\n",a); 14 | scanf("%2d",&a); 15 | } 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /code-c/trail.c: -------------------------------------------------------------------------------- 1 | #include //display trailling zeroes 2 | #define mod 1000000009 3 | 4 | unsigned int find_zero(int x) 5 | { 6 | int count=0; 7 | 8 | while(x) 9 | { 10 | count+=x/5; 11 | x=x/5; 12 | } 13 | return count; 14 | } 15 | 16 | int main() 17 | { 18 | unsigned int a,b; 19 | 20 | scanf("%d",&a); 21 | 22 | while(a--) 23 | { 24 | scanf("%d",&b); 25 | printf("%d\n",find_zero(b)); 26 | } 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /code-cpp/abcdef.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int N; 5 | vector A; 6 | unordered_map L; 7 | unordered_map R; 8 | 9 | 10 | int main(){ 11 | 12 | ios_base :: sync_with_stdio(false); 13 | 14 | cin >> N; 15 | A.resize(N); 16 | 17 | for (int i = 0; i < N; i++) 18 | cin >> A[i]; 19 | 20 | for (int a = 0; a < N; a++){ 21 | for (int b = 0; b < N; b++){ 22 | for (int c = 0; c < N; c++) 23 | L[A[a] * A[b] + A[c]] += 1; 24 | } 25 | } 26 | for (int d = 0; d < N; d++){ 27 | for (int e = 0; e < N; e++){ 28 | for (int f = 0; f < N; f++){ 29 | if (A[d] != 0) 30 | R[A[d] * (A[e] + A[f])] += 1; 31 | } 32 | } 33 | } 34 | int ways = 0; 35 | for (auto key: L){ 36 | if (R.find(key.first) != R.end()) 37 | ways += L[key.first] * R[key.first]; 38 | } 39 | cout << ways << endl; 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /code-cpp/amifib.cpp: -------------------------------------------------------------------------------- 1 | #include //Check if nth terms is arr fibbonaci number 2 | #include 3 | using std::cout; 4 | using std::cin; 5 | using std::endl; 6 | 7 | long long toInt(char *s) 8 | { 9 | long long unsigned i,n=0; 10 | 11 | for(i=0;i>t; 22 | 23 | while(t){ 24 | 25 | char inp[1001]; 26 | cin>>inp; 27 | 28 | long long unsigned new_inp=toInt(inp),arr[6000]; 29 | arr[0]=1; 30 | arr[1]=1; 31 | 32 | for(i=2;i<6000;i++) 33 | { 34 | arr[i]=arr[i-1]+arr[i-2]; 35 | 36 | if(arr[i]==new_inp){ 37 | cout<<"YES\n"; 38 | break; 39 | } 40 | 41 | if(i==5999) 42 | cout<<"NO\n"; 43 | } 44 | t--; 45 | 46 | } 47 | return 0; 48 | 49 | } 50 | 51 | 52 | 53 | 54 | -------------------------------------------------------------------------------- /code-cpp/atm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define endl "\n" 4 | 5 | int main() 6 | { 7 | int req; float bal; 8 | cout.setf(ios::fixed,ios::floatfield); 9 | cout.precision(2); 10 | cin>>req>>bal; 11 | 12 | if(req%5!=0) cout<bal) cout< 2 | using namespace std; 3 | 4 | typedef long long unsigned ll; 5 | string n; 6 | ll k, t; 7 | 8 | int main(){ 9 | ios :: sync_with_stdio(false); 10 | cin >> t; 11 | while (t--){ 12 | cin >> n; 13 | cin >> k; 14 | 15 | ll ans = 0; 16 | for (auto a : n) 17 | ans = (ans * 10 + a - '0') % k; 18 | cout << ans << endl; 19 | } 20 | 21 | return 0; 22 | } 23 | -------------------------------------------------------------------------------- /code-cpp/catalan.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | /** 6 | * 1 2 7 | * 2 1 8 | * 9 | * 3 10 | * 2 11 | * 1 12 | * 2 13 | * 1 3 14 | * 15 | * */ 16 | 17 | 18 | int numTrees(int n) { 19 | if(n == 0) return 0 ; 20 | 21 | if(n == 1) return 1; 22 | 23 | if(n == 2) return 2; 24 | 25 | int ans = 0; 26 | 27 | for(int i = 1; i<=n; i++){ 28 | ans += numTrees(i-1)*numTrees(n - i); 29 | } 30 | 31 | return ans; 32 | } 33 | 34 | int main(){ 35 | int n; 36 | cin >> n; 37 | cout << numTrees << endl; 38 | 39 | } 40 | -------------------------------------------------------------------------------- /code-cpp/chefque.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | typedef long long unsigned llu; 6 | #define mod 4294967296llu 7 | 8 | vector inserts(mod/2,false); 9 | 10 | int main(){ 11 | 12 | ios::sync_with_stdio(false); 13 | 14 | llu Q,S1,A,B; 15 | llu element, finalSum = 0llu,key; 16 | 17 | cin >> Q >> S1 >> A >> B; 18 | 19 | while(Q--){ 20 | key = S1/2llu; 21 | if( S1%2llu) 22 | { 23 | if(inserts[key] == false) 24 | { 25 | inserts[key] = true; 26 | finalSum += key; 27 | } 28 | } 29 | else 30 | { 31 | if(inserts[key] == true) 32 | { 33 | inserts[key] = false; 34 | finalSum -= key; 35 | } 36 | } 37 | S1 = (A*S1+ B)%mod; 38 | } 39 | 40 | cout< 2 | #include 3 | 4 | using namespace std; 5 | 6 | typedef long long unsigned llu; 7 | 8 | llu i,j,n,k,t,temp,maxm,limit; 9 | 10 | llu dpmaxm (vector kind,vector prof,llu k,llu n) 11 | { 12 | vectorx(n); 13 | 14 | x[0]=k/kind[0]; 15 | maxm=x[0]*prof[0]; 16 | 17 | for(i=1; imaxm?x[i]*prof[i]:maxm; 21 | 22 | } 23 | 24 | cout<>t; 31 | 32 | while(t) 33 | { 34 | cin>>n>>k; 35 | 36 | vector kind; 37 | vector prof; 38 | 39 | for(i=0; i>temp; 41 | kind.push_back(temp);} 42 | 43 | for(i=0; i>temp; 45 | prof.push_back(temp);} 46 | 47 | dpmaxm(kind,prof,k,n); 48 | 49 | t--; 50 | } 51 | 52 | return 0; 53 | 54 | } 55 | -------------------------------------------------------------------------------- /code-cpp/chrisStr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | string s, x; 5 | int N; 6 | vector nonStar, counts; 7 | int m[3001][26]; 8 | 9 | int solve(){ 10 | for (auto pos : nonStar){ 11 | // cout << "\n pos: " << pos << " s[pos]: " << s[pos] << " : " << int(s[pos]) - 97; 12 | int match = m[pos][int(s[pos]) - 97]; 13 | counts.push_back(match); 14 | } 15 | sort(counts.begin(), counts.end()); 16 | if (counts.size() <= 1) 17 | return N; 18 | return counts[1]; 19 | } 20 | 21 | int main(){ 22 | ios :: sync_with_stdio(false); 23 | cin >> s; 24 | cin >> N; 25 | 26 | for (int i = 0; i < s.size(); i++){ 27 | if (s[i] != '*') 28 | nonStar.push_back(i); 29 | } 30 | 31 | for (int i = 0; i < N; i++){ 32 | cin >> x; 33 | for (int j = 0; j < s.size(); j++) 34 | m[j][int(x[j]) - 97]++; 35 | } 36 | cout << solve() << endl; 37 | 38 | } 39 | -------------------------------------------------------------------------------- /code-cpp/cnote.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #define llu long long unsigned 4 | 5 | int main() 6 | { 7 | llu n,x,k,p,c,y; int t,flag; 8 | std::cin>>t; 9 | 10 | while (t--) 11 | { 12 | std::cin>>x>>y>>k>>n; 13 | flag=0; 14 | 15 | while (!flag && n) 16 | { 17 | std::cin>>p>>c; 18 | if (p>=(x-y) && k>=c) 19 | {flag=1; break;} 20 | n--; 21 | } 22 | if (flag) 23 | std::cout<<"LuckyChef\n"; 24 | else std::cout<<"UnluckyChef\n"; 25 | t--; 26 | } 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /code-cpp/colTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define mod 1000000007 5 | 6 | int N, T, K, u, v; 7 | vector > A; 8 | 9 | 10 | int main(){ 11 | cin >> T; 12 | while (T --){ 13 | cin >> N >> K; 14 | A.resize(N, vector(N, 0)); 15 | for (int i = 0; i < N - 1; i++){ 16 | cin >> u >> v; 17 | A[u - 1][v - 1] = 1; 18 | } 19 | 20 | } 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /code-cpp/colorfulNo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int colorful(int N) { 6 | vector A; 7 | while (N > 0){ 8 | A.push_back(N % 10); 9 | N /= 10; 10 | } 11 | reverse(A.begin(), A.end()); 12 | 13 | set s; 14 | for (int i = 0; i < A.size(); i++){ 15 | for (int j = i; j < A.size(); j++){ 16 | int num = 1; 17 | for (int k = i; k <= j; k++) 18 | num *= A[k]; 19 | // cout << " Num: "<< num << endl; 20 | if (s.find(num) != s.end()) 21 | 22 | return 0; 23 | s.insert(num); 24 | } 25 | } 26 | 27 | return 1; 28 | } 29 | 30 | 31 | int main(){ 32 | int A; 33 | cin >> A; 34 | cout << colorful(A); 35 | } 36 | -------------------------------------------------------------------------------- /code-cpp/coolGuy.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define MOD 1000000007 4 | typedef long long unsigned llu; 5 | 6 | llu N; 7 | vector A; 8 | 9 | llu f(llu a, llu b){ 10 | llu minE = A[a]; 11 | for (llu i = a; i <= b; i ++) 12 | if (A[i] < minE) 13 | minE = A[i]; 14 | return minE; 15 | } 16 | 17 | void solve(){ 18 | llu ans = 0; 19 | for (int a = 0; a < N; a ++) 20 | for (llu b = a; b < N; b ++) 21 | for(llu c = b + 1; c < N; c++) 22 | for (llu d = c; d < N; d ++) 23 | ans = (ans + min(f(a, b), f(c, d)) % MOD); 24 | cout << ans << endl; 25 | } 26 | 27 | int main(){ 28 | cin >> N; 29 | A.resize(N); 30 | 31 | for (llu i = 0; i < N; i++) 32 | cin >> A[i]; 33 | 34 | solve(); 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /code-cpp/countAp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define MOD 1000000009 4 | 5 | typedef long long ll; 6 | 7 | int main(){ 8 | ll n; 9 | scanf("%lld", &n); 10 | ll a[n + 1]; 11 | for(ll i = 1; i <= n; i++) 12 | scanf("%lld", &a[i]); 13 | 14 | ll ans = 0; 15 | ll dp[n + 1]; 16 | 17 | memset(dp, 0, n + 1); 18 | for(ll diff = -100; diff <= 100; diff++){ 19 | ll sum[101], cur=0; 20 | memset(sum, 0, sizeof(sum)); 21 | 22 | for(ll i = 1; i <= n; i++){ 23 | dp[i] = 1; 24 | if(a[i] - diff >= 1 && a[i] - diff <= 100) 25 | dp[i] = (sum[a[i] - diff] + dp[i]); 26 | 27 | sum[a[i]] = (sum[a[i]] + dp[i]) % MOD; 28 | cur = (cur + dp[i]) % MOD; 29 | } 30 | // cur = (cur - n)%MOD; 31 | ans = (ans + cur) % MOD; 32 | ans = (ans - n + MOD) % MOD; 33 | } 34 | ans = (ans + n) % MOD; 35 | cout << ans+1 << "\n"; 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /code-cpp/countingSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | #define Max int(1e7) 6 | using namespace std; 7 | 8 | // Counting Sort 9 | int main(){ 10 | ios::sync_with_stdio(false); 11 | 12 | int n, temp; 13 | string s; 14 | vector ar[100]; 15 | cin >> n; 16 | 17 | for (int i = 0; i < n; i++){ 18 | cin >> temp >> s; 19 | if (i < n/2) 20 | ar[temp].push_back("-"); 21 | else 22 | ar[temp].push_back(s); 23 | 24 | } 25 | 26 | for(int i = 0; i < 100; ++ i) 27 | for(int j = 0; j < ar[i].size(); ++ j) 28 | cout << ar[i][j] << " "; 29 | 30 | cout << endl; 31 | 32 | return 0; 33 | } -------------------------------------------------------------------------------- /code-cpp/distSubSeq.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define mod 1000000007 5 | #define MAX 100005 6 | 7 | int t, n; 8 | string s; 9 | int last[255]; 10 | 11 | int dp[MAX]; 12 | 13 | int main(){ 14 | cin >> t; 15 | while (t--){ 16 | memset(dp, 0, MAX); 17 | memset(last, -1, sizeof(last)); 18 | cin >> s; 19 | n = s.size(); 20 | 21 | dp[0] = 1; 22 | for (int i = 1; i <= n; i++){ 23 | dp[i] = (dp[i -1] * 2) % mod; 24 | 25 | if (last[s[i -1]] != -1) 26 | dp[i] = (dp[i] - dp[last[s[i -1]]] + mod) % mod; 27 | 28 | last[s[i -1]] = i -1; 29 | } 30 | cout << dp[n] << endl; 31 | } 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /code-cpp/distinctWin.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | vector dNums(vector &A, int K) { 5 | int N = A.size(); 6 | vector ans; 7 | map M; 8 | 9 | for(int i = 0; i < N; i++){ 10 | M[A[i]] += 1; 11 | if (i - K + 1 >= 0){ 12 | ans.push_back(M.size()); 13 | M[A[i - K +1]] -= 1; 14 | 15 | if (M[A[i - K +1]] == 0) 16 | M.erase(A[i - K +1]); 17 | } 18 | } 19 | return ans; 20 | } 21 | 22 | 23 | int main(){ 24 | int N, K; 25 | cin >> N; 26 | vector A(N); 27 | for (int i = 0; i < N; i++) 28 | cin >> A[i]; 29 | cin >> K; 30 | 31 | for (auto a : dNums(A, K)) 32 | cout << a << " -> "; 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /code-cpp/divB266.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | 6 | int n, t; 7 | string s; 8 | 9 | cin >> n >> t; 10 | cin >> s; 11 | 12 | while (t > 0){ 13 | int i = 0; 14 | while (i < n -1){ 15 | if (s[i] == 'B' && s[i+1]=='G'){ 16 | swap(s[i], s[i + 1]); 17 | i += 2; 18 | } 19 | else i++; 20 | } 21 | t--; 22 | } 23 | cout << s << endl; 24 | 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /code-cpp/expressiveWords: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isopropylcyanide/Competitive-Programming/cf7dd54728c8e816c78904070b199dd709232e28/code-cpp/expressiveWords -------------------------------------------------------------------------------- /code-cpp/fanQuot.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef pair pis; 5 | 6 | bool compare(const pis &a, const pis &b){ 7 | if (a.first < b.first) 8 | return 0; 9 | else if (a.first == b.first) 10 | return a.second < b.second; 11 | return 1; 12 | } 13 | 14 | int main(){ 15 | int n, k, f; 16 | string s; 17 | cin >> n >> k; 18 | 19 | vector p; 20 | for (int i = 0; i < n; i++){ 21 | cin >> s >> f; 22 | p.push_back(make_pair(f, s)); 23 | } 24 | sort(p.begin(), p.end(), compare); 25 | 26 | for (int i = 0; i < k; i++) 27 | cout << p[i].second << endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /code-cpp/fdivgame.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | ll N; 6 | vector A; 7 | 8 | 9 | 10 | int main(){ 11 | ios :: sync_with_stdio(false); 12 | cin.tie(NULL); 13 | 14 | ll tests, temp; 15 | cin >> tests; 16 | 17 | while (tests --){ 18 | cin >> N; 19 | A.resize(N, 0); 20 | for (ll i = 0; i < N; i++){ 21 | cin >> temp; 22 | A.push_back(temp); 23 | } 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /code-cpp/fibDP.cpp: -------------------------------------------------------------------------------- 1 | #include //Find nth terms in fibbonaci using dynamic programming 2 | using namespace std; 3 | 4 | void fibDP(long long unsigned n) 5 | { 6 | long long unsigned arr[n+1]; 7 | arr[0]=arr[1]=1; 8 | 9 | for(int i=2; i<=n; i++) 10 | for(int j=2; j>t; 23 | 24 | while(t){ 25 | cin>>n; 26 | fibDP(n); 27 | t--; 28 | } 29 | return 0; 30 | 31 | } 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /code-cpp/findRepeatedDuplicate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /** 4 | * Given an array of integers nums containing n + 1 integers where each integer is in the range [1, n] 5 | * inclusive. There is only one repeated number in nums, return this repeated number. 6 | */ 7 | 8 | int findDuplicate(vector& nums) { 9 | int n = nums.size(); 10 | 11 | for (int i = 0; i < n; i++) { 12 | int num = abs(nums[i]); 13 | if (nums[num] < 0) { 14 | //booooooom 15 | return num; 16 | } else { 17 | nums[num] = -nums[num]; 18 | } 19 | } 20 | return -1; 21 | } 22 | 23 | int main() { 24 | // vector grid = {3, 1, 3, 4, 2}; 25 | // vector grid = {1, 3, 4, 2, 2}; 26 | vector grid = {1, 2}; 27 | std::cout << findDuplicate(grid) << endl; 28 | return 0; 29 | } -------------------------------------------------------------------------------- /code-cpp/gameWinnerK.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef long long unsigned ll; 5 | 6 | ll T; 7 | ll n, k; 8 | 9 | int main(){ 10 | ios::sync_with_stdio(false); 11 | cin.tie(0); 12 | cin >> T; 13 | string first = "Arpa"; 14 | string second = "Dishant"; 15 | 16 | while (T--){ 17 | cin >> n >> k; 18 | // if (n <= 2){ 19 | // cout << first << endl; 20 | // continue; 21 | // } 22 | cout << ((n % (k + 1) == 0) ? second : first); 23 | } 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /code-cpp/geoCheat.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef long long unsigned ll; 5 | typedef pair pll; 6 | vector A; 7 | int N, a, b; 8 | 9 | ll dist(pll &a, pll&b){ 10 | return pow(a.first - b.first, 2) + pow(a.second - b.second, 2); 11 | } 12 | 13 | ll solve(){ 14 | ll n = A.size(); 15 | ll maxDist = 0; 16 | for (int i = 0; i < n -1; i++){ 17 | for (int j = i + 1; j < n; j++) 18 | maxDist = max(maxDist, dist(A[i], A[j])); 19 | } 20 | return maxDist; 21 | } 22 | 23 | int main(){ 24 | ios :: sync_with_stdio(false); 25 | cin.tie(NULL); 26 | cin >> N; 27 | 28 | for (int i = 0; i < N; i++){ 29 | cin >> a >> b; 30 | A.push_back(make_pair(a, b)); 31 | cout << solve() << endl; 32 | } 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /code-cpp/guessNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /** 4 | * I pick a number from 1 to n. You have to guess which number I picked. 5 | */ 6 | int pick = 6; 7 | 8 | int guess(int num) { 9 | if (num > pick) { 10 | return 1; 11 | } else if (num == pick) { 12 | return 0; 13 | } else { 14 | return -1; 15 | } 16 | } 17 | 18 | int guessNumber(int n) { 19 | int l = 1, r = n; 20 | while (l <= r) { 21 | int mid = l + (r - l) / 2; 22 | int res = guess(mid); 23 | 24 | if (res == 0) { 25 | return mid; 26 | } else if (res == 1) { 27 | l = mid + 1; 28 | } else { 29 | r = mid - 1; 30 | } 31 | } 32 | return pick; 33 | } 34 | 35 | int main() { 36 | std::cout << guessNumber(10) << endl; 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /code-cpp/guessNumberII.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | /** 4 | * I pick a number from 1 to n. You have to guess which number I picked. 5 | */ 6 | int dp[205][205]; 7 | int f(int l, int r) { 8 | if (l >= r) { 9 | //no cost 10 | dp[l][r] = 0; 11 | return 0; 12 | } 13 | if (dp[l][r] != -1) { 14 | return dp[l][r]; 15 | } 16 | //cost(1,n)=i+max(cost(1,i−1),cost(i+1,n)) 17 | int ans = INT_MAX; 18 | int mid = (l + r) / 2; 19 | for (int i = mid; i <= r; i++) { 20 | int _ans = i + max(f(l, i - 1), f(i + 1, r)); 21 | ans = min(ans, _ans); 22 | } 23 | dp[l][r] = ans; 24 | return ans; 25 | } 26 | int getMoneyAmount(int n) { 27 | for (int i = 0; i < 205; i++) { 28 | for (int j = 0; j < 205; j++) { 29 | dp[i][j] = -1; 30 | } 31 | } 32 | return f(1, n); 33 | } 34 | 35 | int main() { 36 | std::cout << getMoneyAmount(200) << endl; 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /code-cpp/holes.cpp: -------------------------------------------------------------------------------- 1 | #include //display total holes in the text 2 | #include 3 | using namespace std; 4 | 5 | int get_hole(char a) 6 | { 7 | switch(a) 8 | { 9 | case 'A': case 'D': case 'O': case 'P': case 'Q': case 'R': return 1; break; 10 | case 'B': return 2; break; 11 | default : return 0; 12 | } 13 | 14 | } 15 | int main() 16 | { 17 | int t; char s[100]; 18 | cin>>t; 19 | 20 | while(t<=40 && t--) 21 | { 22 | int count=0; 23 | cin>>s; 24 | for(int i=0; i 2 | 3 | bool isPowerOfFourBasic(int n) { 4 | if (n <= 0) { 5 | return 0; 6 | } 7 | double x = log(n) / log(4); 8 | int _floor = floor(x); 9 | int _ceil = ceil(x); 10 | std::cout << x << endl; 11 | std::cout << _floor << endl; 12 | std::cout << _ceil << endl; 13 | return _floor == _ceil; 14 | } 15 | 16 | bool isPowerOfFour(int n) { 17 | int onesInOdd = 0b1010101010101010101010101010101; 18 | // stringstream res; 19 | // res << hex << onesInOdd << endl; 20 | // std::cout << res.str(); 21 | return n > 0 && (n & n - 1) == 0 && ((n & onesInOdd) == n); 22 | } 23 | 24 | int main() { 25 | std::cout << isPowerOfFour(4) << endl; 26 | std::cout << isPowerOfFour(1304) << endl; 27 | std::cout << isPowerOfFour(625) << endl; 28 | std::cout << isPowerOfFour(256) << endl; 29 | return 0; 30 | } -------------------------------------------------------------------------------- /code-cpp/lisSpoj.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | ll T, N; 6 | vector A; 7 | 8 | ll nlogn_lis(vector &A, ll N){ 9 | //report the length of the lis in O(nlogn) time 10 | vector I(N + 1, 0); 11 | ll length = 1; 12 | I[1] = A[0]; 13 | 14 | for (ll i = 1; i < N; i++){ 15 | //find the upper bound for A[i] in length array 16 | ll upper = upper_bound(I.begin() + 1, I.begin() + 1 + length, A[i] -1) - I.begin(); 17 | //if upperbound > length, increment length 18 | I[upper] = A[i]; 19 | if (upper > length) 20 | length++; 21 | 22 | for (int i = 1; i <= N; i++) 23 | cout << I[i] << " "; 24 | cout << endl; 25 | } 26 | return length; 27 | } 28 | 29 | int main(){ 30 | scanf("%lld", &N); 31 | A.resize(N, 0); 32 | for (int i = 0; i < N; i++) 33 | cin >> A[i]; 34 | 35 | printf("%lld\n", nlogn_lis(A, N)); 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /code-cpp/lockSeq.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | ll N; 6 | 7 | #define mod 1000000007 8 | 9 | vector P = {0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0}; 10 | ll dp[100005][10]; 11 | 12 | ll f(ll i, ll last){ 13 | ll ans = dp[i][last]; 14 | if (ans != -1) 15 | return ans; 16 | ans = 0; 17 | if (i == N) 18 | ans = 1; 19 | else{ 20 | for (ll dig = 0; dig < 10; dig++){ 21 | if (i == 0) 22 | ans = (ans + f(i + 1, dig)) % mod; 23 | else if (!P[dig + last]) 24 | ans = (ans + f(i + 1, dig)) % mod; 25 | } 26 | } 27 | dp[i][last] = ans % mod; 28 | return ans; 29 | } 30 | 31 | 32 | 33 | int main(){ 34 | memset(dp, -1, sizeof(dp)); 35 | cin >> N; 36 | cout << f(0, 0) << endl; 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /code-cpp/longestSubstrWithAtmostKDistinct.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int lengthOfLongestSubstringKDistinct(std::string nums, int k) { 6 | std::map numCount; 7 | int l = 0, ans = 0; 8 | for (int r = 0; r < nums.size(); r++) { 9 | if (numCount[nums[r]] == 0) { 10 | k = k - 1; 11 | } 12 | numCount[nums[r]] += 1; 13 | while (k < 0) { 14 | numCount[nums[l]] = numCount[nums[l]] - 1; 15 | if (numCount[nums[l]] == 0) { 16 | k += 1; 17 | } 18 | l += 1; 19 | } 20 | ans = std::max(ans, (r - (l - 1))); 21 | } 22 | return ans; 23 | } 24 | 25 | 26 | int main() { 27 | std::cout << lengthOfLongestSubstringKDistinct("eceba", 2) << std::endl; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /code-cpp/mandy_swag.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef long long int llu; 5 | 6 | int main(){ 7 | 8 | llu N,temp; 9 | vectorlis; 10 | 11 | scanf("%lld",&N); 12 | 13 | for(llu i=0; i 2 | using namespace std; 3 | 4 | #define MAX 100005 5 | vector adj[MAX]; 6 | 7 | bool vis[MAX]; 8 | int N, M, u, v, edges = 0; 9 | 10 | void dfs(int i){ 11 | vis[i] = 1; 12 | for (auto k : adj[i]){ 13 | edges ++; 14 | if (!vis[k]) 15 | dfs(k); 16 | } 17 | } 18 | 19 | int main(){ 20 | ios :: sync_with_stdio(0); 21 | cin.tie(0); 22 | 23 | cin >> N >> M; 24 | 25 | while (M--){ 26 | cin >> u >> v; 27 | adj[u].push_back(v); 28 | adj[v].push_back(u); 29 | } 30 | int maxVal = 0; 31 | for (int i = 1; i <= N; i++){ 32 | if (!vis[i]) 33 | dfs(i); 34 | maxVal = max(maxVal, edges/2); 35 | edges = 0; 36 | } 37 | cout << maxVal << "\n"; 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /code-cpp/maxElemStack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | stack s; 4 | stack maxStack; 5 | 6 | int main(){ 7 | int n, query, elem; 8 | cin >> n; 9 | maxStack.push(-1); 10 | 11 | while(n--){ 12 | cin >> query; 13 | if (query == 1){ 14 | // push to Stack; 15 | cin >> elem; 16 | if (elem >= maxStack.top()) 17 | maxStack.push(elem); 18 | s.push(elem); 19 | } 20 | else if (query == 2){ 21 | // pop from stack 22 | if (s.top() == maxStack.top()) 23 | maxStack.pop(); 24 | s.pop(); 25 | } 26 | else if (query == 3){ 27 | cout << maxStack.top() < 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | typedef pair pll; 6 | 7 | vector< vector> gg; 8 | ll N, M, K, a, b, x; 9 | vector A; 10 | 11 | int main(){ 12 | ios :: sync_with_stdio(false); 13 | cin >> N >> M >> K; 14 | 15 | A.resize(N + 1); 16 | gg.resize(N + 1); 17 | for (int i = 1; i <= N; i++) 18 | cin >> A[i]; 19 | 20 | while (M--){ 21 | cin >> a >> b; 22 | gg[a].push_back(make_pair(-A[b], -b)); 23 | gg[b].push_back(make_pair(-A[a], -a)); 24 | } 25 | 26 | 27 | for (int i = 1; i <= N; i++){ 28 | ll adj = gg[i].size(); 29 | if (K > adj) 30 | cout << "-1\n"; 31 | else { 32 | sort(gg[i].begin(), gg[i].end()); 33 | cout << -(gg[i][K -1].second) << "\n"; 34 | } 35 | // cout << -(*g[i].find_by_order(K -1)).second << "\n"; 36 | } 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /code-cpp/monkXorTree.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define mp make_pair 5 | #define MAX 100005 6 | typedef long long ll; 7 | 8 | typedef pair pii; 9 | ll res = 0; 10 | 11 | ll N, K, a, b; 12 | vector adj[MAX]; 13 | ll A[MAX], dp[1 << 21]; 14 | 15 | void dfs(ll i, ll par, ll _xor){ 16 | // Traverse tree and store level and parents 17 | _xor ^= A[i]; 18 | res += dp[_xor ^ K]; 19 | dp[_xor]++; 20 | 21 | for (auto neigh : adj[i]){ 22 | if (neigh != par) 23 | dfs(neigh, i, _xor); 24 | } 25 | dp[_xor]--; 26 | } 27 | 28 | int main(){ 29 | cin >> N >> K; 30 | 31 | for (ll i = 1; i <= N; i++) 32 | cin >> A[i]; 33 | 34 | for (ll i = 1; i < N; i++){ 35 | cin >> b; 36 | a = i + 1; 37 | adj[b].push_back(a); 38 | adj[a].push_back(b); 39 | } 40 | dp[0] = 1; 41 | dfs(1, 1, 0); 42 | cout << res<< "\n"; 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /code-cpp/nextGreaterElemI: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isopropylcyanide/Competitive-Programming/cf7dd54728c8e816c78904070b199dd709232e28/code-cpp/nextGreaterElemI -------------------------------------------------------------------------------- /code-cpp/nondec.cpp: -------------------------------------------------------------------------------- 1 | #include //To find the length of the longest non decreasing sequence 2 | #include 3 | using namespace std; 4 | 5 | void print(vectorS,int n) 6 | { 7 | for(int i=0; i>n; 16 | int V[n]; vectorS(n,1); 17 | 18 | for(int i=0; i>V[i]; 19 | 20 | for(int i=0; i 2 | using namespace std; 3 | 4 | #define MAX 100005 5 | typedef long long ll; 6 | 7 | ll L, R; 8 | vector P(MAX); 9 | 10 | 11 | ll func(ll N){ 12 | // bool odd = N & 1; 13 | ll F = 0; 14 | 15 | for (ll i = 1; i * i <= N; i++){ 16 | if (N % i == 0){ 17 | F += int(pow(-1, N/i)) * i; 18 | if (i != N/i) 19 | F += int(pow(-1, i)) * (N/i); 20 | } 21 | } 22 | return -F; 23 | } 24 | 25 | int main(){ 26 | ios :: sync_with_stdio(false); 27 | cin.tie(NULL); 28 | 29 | for (int i = 1; i <= MAX; i++) 30 | P[i] = func(i); 31 | 32 | 33 | ll testcases; 34 | cin >> testcases; 35 | while (testcases --){ 36 | cin >> L >> R; 37 | 38 | ll ans = 0; 39 | for (int i = L; i <= R; i++) 40 | ans += P[i]; 41 | cout << ans << endl; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /code-cpp/powerSet.cpp: -------------------------------------------------------------------------------- 1 | #include //Print powerset in fastest way 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main(){ 8 | int i,n,j; 9 | 10 | cout<<"\nEnter number of elements: "; cin>>n; 11 | cout<<"Enter elements of set : "; 12 | vector set; 13 | 14 | for(i=0; i>j; 16 | set.push_back(j); 17 | } 18 | int max=pow(2,n),count; 19 | 20 | cout<<"\nThe power set is :\n"; 21 | 22 | for(i=0; i>1; 29 | } 30 | cout<<"}"< 2 | #include 3 | using namespace std; 4 | 5 | typedef long long unsigned llu; 6 | 7 | int main() 8 | { 9 | ios :: sync_with_stdio(false); 10 | 11 | llu T, N, X, Y; 12 | cin >> T; 13 | while (T --){ 14 | 15 | cin >> N >> X >> Y; 16 | set moreBetter; 17 | set lessBetter; 18 | for (int i = X ; i < N; i ++) 19 | moreBetter.insert(i + 1); 20 | 21 | for (int i = Y; i > 0; i --) 22 | lessBetter.insert(N - i); 23 | 24 | vector ans; 25 | set_union(moreBetter.begin(), moreBetter.end(), lessBetter.begin(), 26 | lessBetter.end(), inserter(ans, ans.begin()) ); 27 | cout << ans.size(); 28 | } 29 | 30 | return 0; 31 | 32 | } 33 | -------------------------------------------------------------------------------- /code-cpp/rootMinHeap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void heapify(vector &H, int i){ 5 | int left = 2*i + 1, right = 2*i + 2; 6 | int smallest = i; 7 | smallest = (left < H.size() && H[left] < H[i]) ? left : i; 8 | smallest = (right < H.size() && H[right] < H[smallest]) ? right : smallest; 9 | 10 | if (smallest != i){ 11 | swap(H[i], H[smallest]); 12 | heapify(H, smallest); 13 | } 14 | } 15 | 16 | vector buildHeap(vector &A){ 17 | vector H(A); 18 | for (int i = A.size()/2; i >= 0; i--) 19 | heapify(H, i); 20 | 21 | return H; 22 | } 23 | 24 | int main(){ 25 | vector A; 26 | string line; 27 | int c; 28 | getline(cin, line); 29 | istringstream iss(line); 30 | while (iss >> c) 31 | A.push_back(c); 32 | 33 | vector H = buildHeap(A); 34 | cout << *H.begin(); 35 | // make_heap(A.begin(), A.end(), greater()); 36 | // cout << *A.begin(); 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /code-cpp/rotation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | string s, t; 5 | int n; 6 | 7 | bool matches(int length){ 8 | int endIndex = n - length; 9 | int i = 0; 10 | while (endIndex < n){ 11 | if (s[endIndex++] != t[i++]){ 12 | return false; 13 | } 14 | } 15 | return true; 16 | } 17 | 18 | int main(){ 19 | ios::sync_with_stdio(false); 20 | cin.tie(0); 21 | cin >> n >> s >> t; 22 | 23 | int minAns = n; 24 | 25 | for (int i = 1; i < n; i++){ 26 | if (matches(i)){ 27 | minAns = n - i; 28 | // break; 29 | } 30 | } 31 | cout << minAns << "\n"; 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /code-cpp/stoneDiv.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | 6 | int main() { 7 | 8 | ll n, m; 9 | cin >> n >> m; 10 | 11 | ll nimsum = 0; 12 | for (ll i = 0; i < m; ++i) { 13 | ll x, k = 0; 14 | cin >> x; 15 | 16 | if (x > 0) 17 | while ((x & 1) == 0){ 18 | k++; 19 | x >>= 1; 20 | } 21 | 22 | 23 | nimsum ^= k; 24 | } 25 | 26 | if (nimsum != 0) 27 | printf("First\n"); 28 | else 29 | printf("Second\n"); 30 | 31 | } 32 | -------------------------------------------------------------------------------- /code-cpp/subtreeRemoval.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define MAX 100005 5 | typedef long long ll; 6 | ll A[MAX]; 7 | vector G[MAX]; 8 | 9 | void clearGraph(){ 10 | for (auto nodeList : G){ 11 | std::fill(nodeList.begin(), nodeList.end(), 0); 12 | } 13 | } 14 | 15 | ostream & operator<<(ostream &c, vector &T){ 16 | for (auto t : T){ 17 | c << t << " "; 18 | } 19 | return c; 20 | } 21 | 22 | int main() { 23 | std::ios::sync_with_stdio(false); 24 | cin.tie(0); 25 | ll testcases, N, X, u, v, tmp; 26 | 27 | cin >> testcases; 28 | while (testcases --){ 29 | cin >> N >> X; 30 | for (int i = 1; i <= N; i++){ 31 | cin >> A[i]; 32 | } 33 | clearGraph(); 34 | 35 | for (int i = 0; i < N -1; i++){ 36 | cin >> u >> v; 37 | G[u].push_back(v); 38 | G[v].push_back(u); 39 | } 40 | } 41 | return 0; 42 | } -------------------------------------------------------------------------------- /code-cpp/ternarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int N, l, r; 5 | // find the maxm value of function in range l - r 6 | 7 | double f(double x){ 8 | return 2*x*x - 12*x + 7; 9 | } 10 | 11 | double searchMax(int start, int end){ 12 | // Find the maxm x for {start, end} 13 | double l = start, r = end; 14 | 15 | for (int i = 0; i < 200; i++){ 16 | double l1 = (2*l + r)/ 3; 17 | double l2 = (l + 2*r)/ 3; 18 | // cout << "\n l1 : " << l1 << " l2: " << l2; 19 | double a = f(l1), b = f(l2); 20 | // cout << "\n f(l1) : " << a << " f(l2): " << b; 21 | if (a > b) 22 | l = l1; 23 | else r = l2; 24 | } 25 | // cout << "\n At the end: l: " << l << endl; 26 | return f(l); 27 | } 28 | 29 | int main(){ 30 | cin >> N; 31 | for (int i = 0; i < N; i++){ 32 | cin >> l >> r; 33 | double ans = searchMax(l, r); 34 | cout << fixed << setprecision(0) << ans << endl; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /code-cpp/varArrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | typedef long long unsigned llu; 10 | unordered_set mySet; 11 | 12 | int main() { 13 | ios :: sync_with_stdio(false); 14 | llu N, S, P, Q; 15 | cin >> N >> S >> P >> Q; 16 | 17 | vector ans(N); 18 | ans[0] = S & ((1llu << 31llu) - 1llu); 19 | mySet.insert(ans[0]); 20 | for (llu i = 1; i < N; i++){ 21 | ans[i] = (ans[i - 1]*P + Q) & ((1llu << 31llu) - 1llu); 22 | mySet.insert(ans[i]); 23 | } 24 | 25 | cout << mySet.size()< 2 | using namespace std; 3 | 4 | int T, N; 5 | 6 | int main(){ 7 | ios::sync_with_stdio(false); 8 | cin.tie(0); 9 | 10 | return 0; 11 | } -------------------------------------------------------------------------------- /code-cpp/xennyClass.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | string populate(int N, int tog){ 5 | //Populate string starting from B/G first 6 | string s = ""; 7 | for (int i = 0; i < 2*N; i++){ 8 | if (tog == 0) 9 | s += 'B'; 10 | else s += 'G'; 11 | tog ^= 1; 12 | } 13 | return s; 14 | } 15 | 16 | int minSwaps(int N, string &s){ 17 | // Let B = 0, G = 1 18 | string a = populate(N, 0); 19 | string b = populate(N, 1); 20 | 21 | int cA = 0, cB = 0; 22 | 23 | for (int i = 0; i < 2*N; i++){ 24 | if (s[i] != a[i]) 25 | cA ++; 26 | else if (s[i] != b[i]) 27 | cB ++; 28 | } 29 | return min(cA/2, cB/2); 30 | } 31 | 32 | int main(){ 33 | 34 | int testcases, N; 35 | cin >> testcases; 36 | string s; 37 | 38 | while (testcases --){ 39 | cin >> N; 40 | cin >> s; 41 | cout << minSwaps(N, s) << endl; 42 | } 43 | 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /code-cpp/zanSmart.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | int A[105]; 6 | 7 | int main(){ 8 | int n, t; 9 | cin >> n; 10 | for (int i = 0; i < n; i++){ 11 | cin >> t; 12 | A[t]++; 13 | } 14 | int ways = 0; 15 | for (int i = 0; i < 100; i++) 16 | ways += A[i]/2; 17 | cout << ways << endl; 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /code-go/can_permutate.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | /** Given a string s, return true if a permutation of the string could form a palindrome. **/ 6 | 7 | func canPermutePalindrome(s string) bool { 8 | // if length is even, each character must occur even 9 | // if length is odd, each character must occur even except one 10 | n := len(s) 11 | charCounts := make(map[rune]int) 12 | for _, ch := range s{ 13 | charCounts[ch] += 1 14 | } 15 | allEven, oddCounters := true, 0 16 | for _, v := range charCounts{ 17 | if v % 2 != 0 { 18 | allEven = false 19 | oddCounters += 1 20 | } 21 | } 22 | if n % 2 == 0 { 23 | return allEven && oddCounters == 0 24 | } else{ 25 | return oddCounters == 1 26 | } 27 | } 28 | 29 | func main() { 30 | fmt.Println(canPermutePalindrome("code")) 31 | fmt.Println(canPermutePalindrome("aab")) 32 | fmt.Println(canPermutePalindrome("carerac")) 33 | } -------------------------------------------------------------------------------- /code-go/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/isopropylcyanide/code-go 2 | 3 | go 1.17 4 | 5 | require ( 6 | github.com/google/uuid v1.3.0 7 | github.com/stretchr/testify v1.7.1 8 | ) 9 | 10 | require ( 11 | github.com/davecgh/go-spew v1.1.0 // indirect 12 | github.com/google/go-cmp v0.5.9 // indirect 13 | github.com/pmezard/go-difflib v1.0.0 // indirect 14 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c // indirect 15 | ) 16 | -------------------------------------------------------------------------------- /code-go/number_islands.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func numIslands(grid [][]byte) int { 6 | if grid == nil || len(grid) == 0 || len(grid[0]) == 0 { 7 | return 0 8 | } 9 | islands := 0 10 | for i := 0; i < len(grid); i++ { 11 | for j := 0; j < len(grid[0]); j++ { 12 | if grid[i][j] == 1 { 13 | islands += floodFill(i, j, grid) 14 | } 15 | } 16 | } 17 | return islands 18 | } 19 | 20 | func floodFill(i int, j int, grid [][]byte) int { 21 | if isOutOfBounds(i, j, grid) || grid[i][j] != 1 { 22 | return 0 23 | } 24 | grid[i][j] = 0 25 | floodFill(i+1, j, grid) 26 | floodFill(i-1, j, grid) 27 | floodFill(i, j+1, grid) 28 | floodFill(i, j-1, grid) 29 | return 1 30 | } 31 | 32 | func isOutOfBounds(i int, j int, grid [][]byte) bool { 33 | return i < 0 || i >= len(grid) || j < 0 || j >= len(grid[0]) 34 | } 35 | 36 | func main() { 37 | grid := [][]byte{ 38 | {1, 1, 1, 1, 0}, 39 | {1, 1, 0, 1, 0}, 40 | {1, 1, 0, 0, 0}, 41 | {0, 0, 0, 0, 0}, 42 | } 43 | fmt.Println(numIslands(grid)) 44 | } 45 | -------------------------------------------------------------------------------- /code-go/reverseInteger.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func reverseUtil(num, revNum int) int { 9 | if num == 0 { 10 | return revNum 11 | } else { 12 | lastDigit := num % 10 13 | revNum := revNum*10 + lastDigit 14 | if revNum > math.MaxInt32 { 15 | return 0 16 | } 17 | return reverseUtil(num/10, revNum) 18 | } 19 | } 20 | 21 | func abs(x int) (int, int) { 22 | if x < 0 { 23 | return -1, -x 24 | } else { 25 | return 1, x 26 | } 27 | } 28 | func reverse(x int) int { 29 | sgn, val := abs(x) 30 | ans := reverseUtil(val, 0) 31 | return ans * sgn 32 | } 33 | 34 | func main() { 35 | fmt.Println(reverse(-123)) 36 | fmt.Println(reverse(1534236469)) 37 | fmt.Println(int64(reverse(1534236469))) 38 | 39 | } 40 | -------------------------------------------------------------------------------- /code-go/uuid_random.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "strings" 6 | 7 | uuidlib "github.com/google/uuid" 8 | ) 9 | 10 | // idLengthLimit is the max length limit for the ID (library internal) 11 | const idLengthLimit = 12 12 | 13 | // GenerateUniqueID generates a unique ID using a one way function on a new UUID 14 | func GenerateUniqueID() (string, error) { 15 | uuid := uuidlib.New() 16 | uuidStr := strings.Replace(uuid.String(), "-", "", -1) // replace hyphens 17 | uuidStr = uuidStr[(len(uuidStr) - idLengthLimit):] // trim to the desired limit 18 | return strings.ToUpper(uuidStr), nil // upper case 19 | } 20 | 21 | func main() { 22 | for i := 0; i < 10; i++ { 23 | if id, err := GenerateUniqueID(); err == nil { 24 | fmt.Printf("Generated ID %s\n", id) 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /code-go/valid_anagram.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | /** Given two strings s and t, return true if t is an anagram of s, and false otherwise. **/ 6 | 7 | func isAnagram(s string, t string) bool { 8 | // two strings are anagrams if they can be rearranged using the same number of letters 9 | if len(s) != len(t){ 10 | return false 11 | } 12 | charCountsA := make(map[rune]int) 13 | for i:= 0; i < len(s); i++{ 14 | charCountsA[rune(s[i])] += 1 15 | charCountsA[rune(t[i])] -= 1 16 | } 17 | for _, v := range charCountsA{ 18 | if v != 0{ 19 | return false 20 | } 21 | } 22 | return true 23 | } 24 | 25 | func main() { 26 | fmt.Println(isAnagram("anagram", "nagaram")) 27 | fmt.Println(isAnagram("rat", "car")) 28 | } -------------------------------------------------------------------------------- /code-hs/countExperts.hs: -------------------------------------------------------------------------------- 1 | 2 | 3 | main :: IO() 4 | main = do 5 | arr <- getContents 6 | let n = length . filter (\x -> x >= 1600 && x <= 1900) . map (read :: String -> Int) . words . unwords . drop 1 $ lines arr 7 | print n 8 | -------------------------------------------------------------------------------- /code-hs/customOrd.hs: -------------------------------------------------------------------------------- 1 | import Control.Monad 2 | import Data.List 3 | 4 | comparator :: (Ord a, Num a) => a -> a -> Ordering 5 | comparator a b 6 | | abs(a) < abs (b) = LT 7 | | otherwise = GT 8 | 9 | main :: IO() 10 | main = do 11 | a <- getContents 12 | let arr = map read $ words . unwords . drop 1 $ lines a :: [Int] 13 | putStrLn . unwords $ map show (sortBy comparator arr) 14 | -------------------------------------------------------------------------------- /code-hs/devArr.hs: -------------------------------------------------------------------------------- 1 | solver :: Int -> String 2 | solver n 3 | | n `mod` 6 == 0 = "Misha" 4 | | otherwise = "Chef" 5 | 6 | main :: IO() 7 | main = do 8 | arr <- getContents 9 | putStrLn . unlines . map solver . map (read :: String -> Int) . drop 1 $ lines arr 10 | -------------------------------------------------------------------------------- /code-hs/ishanStrings.hs: -------------------------------------------------------------------------------- 1 | import Data.Char 2 | 3 | wrapCharLeft :: Char -> Char 4 | wrapCharLeft x = chr $ 97 +(ord x - 97 -1) `mod` 26 5 | 6 | solve :: String -> String 7 | solve [] = [] 8 | solve ('a' : xs) = 9 | if all (\x -> x == 'a') xs then 10 | (take (length xs) $ cycle "a") ++ "z" 11 | else 12 | let 13 | conv = takeWhile (\x -> x/='a') xs 14 | noConv = dropWhile (\x -> x/='a') xs 15 | in ['a'] ++ (map wrapCharLeft conv) ++ noConv 16 | -- No more conversions possible 17 | solve (x: xs) = let 18 | conv = takeWhile (\x -> x/='a') (x:xs) 19 | noConv = dropWhile (\x -> x/='a') (x:xs) 20 | in (map wrapCharLeft conv) ++ noConv 21 | 22 | 23 | main :: IO() 24 | main = do 25 | a <- getContents 26 | putStrLn . unlines . map (\x -> solve x) . drop 1 $ lines a 27 | -------------------------------------------------------------------------------- /code-hs/life.hs: -------------------------------------------------------------------------------- 1 | 2 | main :: IO() 3 | main = do 4 | a <- getContents 5 | putStrLn . unlines . take (length . drop 1 $ lines a) $ cycle ["Alice"] 6 | -------------------------------------------------------------------------------- /code-hs/maxmin.hs: -------------------------------------------------------------------------------- 1 | import Control.Monad 2 | 3 | solver :: IO() 4 | solver = do 5 | n <- readLn :: IO Int 6 | arr_temp <- getLine 7 | let arr = map read $ words arr_temp :: [Int] 8 | putStrLn $ show $ subtract (minimum arr) (maximum arr) 9 | 10 | main :: IO() 11 | main = do 12 | tests <- readLn :: IO Int 13 | replicateM_ tests solver 14 | -------------------------------------------------------------------------------- /code-hs/morningAssem.hs: -------------------------------------------------------------------------------- 1 | import Data.List 2 | 3 | solver :: [Int] -> [Int] -> Int 4 | solver [] [] = 0 5 | solver (x: xs) (y : ys) = if x /= y then 1 + solver xs ys 6 | else solver xs ys 7 | 8 | main :: IO() 9 | main = do 10 | arr <- map (read :: String -> Int) . words <$> getLine 11 | print $ solver arr (sort arr) 12 | -------------------------------------------------------------------------------- /code-hs/ndiffpal.hs: -------------------------------------------------------------------------------- 1 | 2 | solver :: Int -> String 3 | solver n = take n $ cycle ['a'..'z'] 4 | 5 | main :: IO() 6 | main = do 7 | a <- getContents 8 | putStrLn . unlines . map solver . map (read :: String -> Int) . drop 1 $ lines a 9 | -------------------------------------------------------------------------------- /code-hs/palinSubstr.hs: -------------------------------------------------------------------------------- 1 | 2 | import Control.Monad 3 | import Data.List 4 | 5 | 6 | listIntersect :: String -> String -> IO() 7 | listIntersect a b = do 8 | if (length $ intersect a b) == 0 9 | then putStrLn "No" 10 | else putStrLn "Yes" 11 | 12 | main :: IO() 13 | main = do 14 | t <- readLn :: IO Int 15 | forM_ [1..t] $ \_ -> do 16 | a <- getLine 17 | b <- getLine 18 | listIntersect a b 19 | -------------------------------------------------------------------------------- /code-hs/tricoin.hs: -------------------------------------------------------------------------------- 1 | 2 | f x = floor (0.5 * ((sqrt (8 * x + 1)) -1)) 3 | 4 | main :: IO() 5 | main = do 6 | a <- getContents 7 | putStrLn . unlines . map show $ [f (fromIntegral x) | x <- map (read :: String -> Int) . drop 1 $ lines a] 8 | -------------------------------------------------------------------------------- /code-hs/xentask.hs: -------------------------------------------------------------------------------- 1 | 2 | 3 | import Control.Monad 4 | 5 | -- f :: [Int] -> [Int] -> Int -> Int -> (Int, Int) 6 | f [] [] a b = (a, b) 7 | f [x] [y] a b = (x + b, y + a) 8 | f (x:y:xs) (a:b:as) c d = f xs as (c + x + b) (d + y + a) 9 | 10 | main :: IO() 11 | main = do 12 | t <- readLn :: IO Int 13 | forM_ [1..t] $ \_ -> do 14 | n <- readLn :: IO Int 15 | a <- getLine 16 | let b = 0 :: Int 17 | let xenny = map (read :: String -> Int) $ words a 18 | let yana = map (read :: String -> Int) $ words a 19 | print . minimum $ f xenny yana b b 20 | -------------------------------------------------------------------------------- /code-java/src/main/java/CompositeNum.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.Collections; 3 | import java.util.Scanner; 4 | 5 | class CompositeNum { 6 | static int maxN = 10005; 7 | static ArrayList prime; 8 | 9 | public static void sieveOfEros() { 10 | prime = new ArrayList(Collections.nCopies(maxN, 1)); 11 | prime.set(0, 0); 12 | prime.set(1, 0); 13 | for (int i = 2; i < maxN; i++) { 14 | if (prime.get(i) == 1) { 15 | for (int j = i * i; j < maxN; j += i) 16 | prime.set(j, 0); 17 | } 18 | } 19 | } 20 | 21 | public static void main(String[] args) { 22 | sieveOfEros(); 23 | Scanner s = new Scanner(System.in); 24 | int N = s.nextInt(); 25 | 26 | for (int i = 2; i <= N; i++) 27 | if (prime.get(i) == 0) 28 | System.out.print(i + " "); 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /code-js/hello.js: -------------------------------------------------------------------------------- 1 | // Javascript hello world 2 | 3 | var hello = function() { 4 | // Print hello on the console. 5 | console.log("i am saying hello"); 6 | console. 7 | }; 8 | 9 | hello(); 10 | -------------------------------------------------------------------------------- /code-py/2darray.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | 4 | 5 | def f(a): 6 | ones, twos = 0, 0 7 | for i in xrange(len(a)): 8 | twos |= (ones & a[i]) 9 | ones ^= a[i] 10 | 11 | cbm = ~(ones & twos) 12 | ones &= cbm 13 | twos &= cbm 14 | return ones 15 | 16 | 17 | def hourGlass(a): 18 | maxm = -sys.maxint 19 | for i in xrange(len(arr) - 3 + 1): 20 | summ = 0 21 | for j in xrange(1, len(arr[0]) - 1): 22 | summ = sum([arr[i][j - 1], arr[i][j], arr[i][j + 1], arr[i + 1] 23 | [j], arr[i + 2][j - 1], arr[i + 2][j], arr[i + 2][j + 1]]) 24 | if maxm < summ: 25 | maxm = summ 26 | print maxm 27 | 28 | arr = [] 29 | for _ in xrange(6): 30 | arr_temp = map(int, raw_input().split()) 31 | arr.append(arr_temp) 32 | hourGlass(arr) 33 | -------------------------------------------------------------------------------- /code-py/allParentPairs.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : integer 3 | # @return a list of strings 4 | 5 | def generateParenthesis(self, A): 6 | def genAllParen(s, l, r): 7 | if l > r: 8 | return 9 | 10 | if l == A and r == A: 11 | res.append(s) 12 | else: 13 | return genAllParen(s + '(', l + 1, r) 14 | if l > r: 15 | return genAllParen(s + ')', l, r + 1) 16 | 17 | allPair = set() 18 | res = [] 19 | if A == 0: 20 | return res 21 | genAllParen('', 0, 0) 22 | print res 23 | return allPair 24 | 25 | if __name__ == '__main__': 26 | import sys 27 | print Solution().generateParenthesis(int(sys.argv[1])) 28 | 29 | 30 | # 31 | -------------------------------------------------------------------------------- /code-py/allocarry.py: -------------------------------------------------------------------------------- 1 | 2 | def main(): 3 | N = int(input()) 4 | _odd_sum = _even_sum = 0 5 | _sub_allocarry = [] 6 | 7 | for _ in range(N): 8 | num = list(map(int, input())) 9 | # _odd_sum = _even_sum = 0 10 | for ind, i in enumerate(num): 11 | if ind % 2 == 0: 12 | _even_sum += i 13 | else: 14 | _odd_sum += i 15 | 16 | _sub_allocarry.append(_even_sum - _odd_sum) 17 | 18 | # print (_odd_sum, _even_sum, abs(_even_sum - _odd_sum)) 19 | # print (_sub_allocarry) 20 | _odd_alloc = _even_alloc = 0 21 | 22 | for ind, i in enumerate(_sub_allocarry): 23 | if ind % 2 == 0: 24 | _even_alloc += i 25 | else: 26 | _odd_alloc += i 27 | 28 | # print (_even_alloc, _odd_alloc) 29 | print (_even_alloc - _odd_alloc) 30 | 31 | 32 | if __name__ == "__main__": 33 | main() 34 | -------------------------------------------------------------------------------- /code-py/alost.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | if __name__ == '__main__': 4 | for _ in xrange(input()): 5 | N, P, Q = map(int, raw_input().split()) 6 | A = map(int, raw_input().split()) 7 | A.sort() 8 | count = 0 9 | 10 | if P == 0: 11 | for i in A: 12 | if i % 2 == 0 and i / 2 <= Q: 13 | Q -= i / 2 14 | count += 1 15 | elif Q == 0: 16 | for i in A: 17 | if i <= P: 18 | P -= i 19 | count += 1 20 | else: 21 | for i in A: 22 | x = min(i / 2, Q) 23 | Q -= x 24 | t = i - 2 * x 25 | y = min(P, t) 26 | P, Z = P - y, t - y 27 | if Z == 0: 28 | count += 1 29 | else: 30 | Q, P = Q + x, P + y 31 | 32 | print count 33 | -------------------------------------------------------------------------------- /code-py/annualParty.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | for _ in xrange(input()): 3 | A, B, C = [], [], [] 4 | N = input() 5 | for i in xrange(N): 6 | a, b, c = map(int, raw_input().split()) 7 | A.append(a) 8 | B.append(b) 9 | C.append(c) 10 | 11 | satisfy = 0 12 | for m in xrange(pow(2, N)): 13 | if m == 0: 14 | continue 15 | mask = bin(m)[2:].zfill(N) 16 | tA, tB, tC = 0, 0, 0 17 | count = 0 18 | for i, j in enumerate(mask): 19 | if j == '1': 20 | count += 1 21 | tA = max(tA, A[i]) 22 | tB = max(tB, B[i]) 23 | tC = max(tC, C[i]) 24 | if tA + tB + tC <= 10000: 25 | satisfy = max(satisfy, count) 26 | 27 | print 'Case #%d: %d' % (_ + 1, satisfy) 28 | -------------------------------------------------------------------------------- /code-py/antiDiagonals.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param a : list of list of integers 3 | # @return a list of list of integers 4 | 5 | def diagonal(self, M): 6 | ans = [] 7 | row, col = len(M), len(M[0]) 8 | for line in xrange(1, row + col): 9 | subAns = [] 10 | start = max(0, line - row) 11 | count = min(line, col - start, row) 12 | 13 | for j in xrange(count): 14 | subAns.append(M[min(row, line) - j - 1][start + j]) 15 | 16 | ans.append(subAns) 17 | 18 | for i in ans: 19 | print i 20 | return ans 21 | 22 | 23 | def main(): 24 | M = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 25 | Solution().diagonal(M) 26 | 27 | if __name__ == '__main__': 28 | main() 29 | 30 | 31 | # 32 | 33 | 34 | # 35 | -------------------------------------------------------------------------------- /code-py/arrRot.py: -------------------------------------------------------------------------------- 1 | 2 | def rotate(K, N, A): 3 | K = K % N 4 | B = [0] * N 5 | for ind, i in enumerate(A): 6 | B[ind] = A[(ind - K) % N] 7 | return B 8 | 9 | if __name__ == '__main__': 10 | for _ in xrange(input()): 11 | N, K = map(int, raw_input().split()) 12 | A = map(int, raw_input().split()) 13 | B = rotate(K, N, A) 14 | for i in B: 15 | print i, 16 | -------------------------------------------------------------------------------- /code-py/arrays.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | # @param A : list of integers 4 | # @return a list of integers 5 | 6 | def plusOne(self, A): 7 | num = A[-1] + 1 8 | if num / 10 > 0: 9 | carry = num / 10 10 | else: 11 | carry = 0 12 | A[-1] = num % 10 13 | 14 | for i in xrange(len(A) - 2, -1, -1): 15 | if carry > 0: 16 | num = A[i] + carry 17 | A[i] = num % 10 18 | carry = num / 10 19 | 20 | if carry: 21 | return [carry] + A 22 | else: 23 | if A[0] == 0: 24 | for i in xrange(1, len(A)): 25 | if A[i] != 0: 26 | return A[i:] 27 | else: 28 | return A 29 | 30 | 31 | def main(): 32 | s = Solution() 33 | print s.plusOne(map(int, raw_input().split())) 34 | 35 | if __name__ == '__main__': 36 | main() 37 | -------------------------------------------------------------------------------- /code-py/ashu_prime.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | """ 4 | Given a prime number X, you need to give the count of all numbers 5 | in range 1 to 10**6 inclusive which have minimum prime factor X. 6 | """ 7 | 8 | 9 | def seq_sieve(n): 10 | F = [0] * (n + 1) 11 | i = 2 12 | 13 | while i * i <= n: 14 | if F[i] == 0: 15 | k = i * i 16 | 17 | while k <= n: 18 | if F[k] == 0: 19 | F[k] = i 20 | 21 | k += i 22 | i += 1 23 | 24 | return F 25 | 26 | 27 | def main(): 28 | L = Counter(seq_sieve(10**6)) 29 | # print L 30 | for testcases in xrange(input()): 31 | print L[input()] + 1 32 | 33 | if __name__ == '__main__': 34 | main() 35 | -------------------------------------------------------------------------------- /code-py/astring.py: -------------------------------------------------------------------------------- 1 | 2 | # smallest lexicographical subsequence of string S of length K. 3 | 4 | 5 | def solveDP(X, K, debug=False): 6 | N = len(X) 7 | T = [["" for i in xrange(N + 1)] for j in xrange(K + 1)] 8 | 9 | for i in xrange(1, K + 1): 10 | for j in xrange(1, N + 1): 11 | if i == j: 12 | T[i][j] = T[i - 1][j - 1] + X[j - 1] 13 | elif j > i: 14 | T[i][j] = min(T[i][j - 1], 15 | T[i - 1][j - 1] + X[j - 1]) 16 | if debug: 17 | for i in T: 18 | print i 19 | return T[K][N] 20 | 21 | 22 | if __name__ == '__main__': 23 | 24 | for _ in xrange(input()): 25 | X = raw_input() 26 | K = input() 27 | print solveDP(X, K, True) 28 | -------------------------------------------------------------------------------- /code-py/babySteps.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | for _ in xrange(input()): 4 | A, B, D = map(int, raw_input().split()) 5 | if D == 0: 6 | print D 7 | elif D == A or D == B: 8 | print 1 9 | elif A > D: 10 | print 2 11 | else: 12 | steps = 0 13 | while D > 2 * B: 14 | steps += 1 15 | D -= B 16 | steps += 2 17 | print steps 18 | -------------------------------------------------------------------------------- /code-py/backToorig.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | x, y = map(int, raw_input().split()) 4 | N = input() 5 | a, b = 0, 0 6 | for _ in xrange(N): 7 | u, v = map(int, raw_input().split()) 8 | a += u 9 | b += v 10 | print x - a, y - b 11 | -------------------------------------------------------------------------------- /code-py/bagapple.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | n=int(sys.stdin.readline()) 4 | lis=map(int,raw_input().split()) 5 | l=sum(lis) 6 | 7 | if l%3==0: 8 | print l 9 | else: 10 | hash={} 11 | for i in xrange(n): 12 | hash[i]=[k for k in lis] 13 | hash[i].remove(hash[i][i]) 14 | hash[i]=sum(hash[i]) 15 | 16 | print max([i for i in hash.values() if i%3==0]) -------------------------------------------------------------------------------- /code-py/balStrLen.py: -------------------------------------------------------------------------------- 1 | def solve(S): 2 | n = len(S) 3 | dp = [[0 for j in xrange(n)] for i in xrange(n)] 4 | 5 | for l in xrange(1, n): 6 | for i in xrange(0, n - l): 7 | j = i + 1 8 | if S[i] == '(' and S[j] == ')': 9 | # balanced 10 | if dp[i + 1][j - 1] + 2 > dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]: 11 | dp[i][j] = dp[i + 1][j - 1] + 2 12 | else: 13 | dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1] 14 | else: 15 | if dp[i + 1][j] > dp[i][j - 1]: 16 | dp[i][j] = dp[i + 1][j] 17 | else: 18 | dp[i][j] = dp[i][j - 1] 19 | 20 | return dp[0][n - 1] 21 | 22 | if __name__ == '__main__': 23 | for _ in xrange(input()): 24 | S = raw_input() 25 | print solve(S) 26 | -------------------------------------------------------------------------------- /code-py/base_one.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def base10conv(n, b): 4 | if n < b: 5 | return str(n) 6 | else: 7 | rem = n % b 8 | return base10conv(n / b, b) + str(rem) 9 | 10 | 11 | def numBasesStartWithOne(N): 12 | count = 0 13 | for i in xrange(2, N + 1): 14 | co = base10conv(N, i) 15 | if co[0] == '1': 16 | count += 1 17 | # print '%d starts with 1 in base %d : %s' % (N, i, co) 18 | return count 19 | 20 | if __name__ == '__main__': 21 | for _ in xrange(input()): 22 | N = input() 23 | if str(N)[0] == '1': 24 | print 'INFINITY' 25 | else: 26 | print numBasesStartWithOne(N) 27 | -------------------------------------------------------------------------------- /code-py/bearVow.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | import re 3 | 4 | vowels = 'aeiouy' 5 | 6 | 7 | def isHard(s): 8 | d = Counter(s) 9 | countVowel = sum(map(lambda x: d[x], vowels)) 10 | countConso = len(s) - countVowel 11 | 12 | if countConso > countVowel: 13 | return 'hard' 14 | # check for three consecutive consonants 15 | reg = re.compile('[bcdfghjklmnpqrstvwxz]{3}') 16 | if reg.search(s) is not None: 17 | return 'hard' 18 | return 'easy' 19 | 20 | if __name__ == '__main__': 21 | for _ in xrange(input()): 22 | print isHard(raw_input()) 23 | -------------------------------------------------------------------------------- /code-py/beautArray.py: -------------------------------------------------------------------------------- 1 | from math import log as l 2 | 3 | 4 | def isBeaut(): 5 | if 0 in A: 6 | return True 7 | h = set() 8 | 9 | for i in xrange(N): 10 | t = l(abs(A[i])) / l(2) 11 | A[i] = t if A[i] > 0 else -t 12 | # log tables prepared 13 | print A 14 | for i in A: 15 | val, sgn = abs(i), i > 0 16 | if (val, sgn) in h: 17 | return True 18 | else: 19 | h.add((val, sgn)) 20 | print h 21 | 22 | return False 23 | 24 | if __name__ == '__main__': 25 | for _ in xrange(input()): 26 | N = input() 27 | A = map(int, raw_input().split()) 28 | print 'yes' if isBeaut() else 'no' 29 | -------------------------------------------------------------------------------- /code-py/beautPairs.py: -------------------------------------------------------------------------------- 1 | 2 | def intersect(A, B): 3 | i, j, ans = 0, 0, 0 4 | 5 | while i < len(A) and j < len(B): 6 | if A[i] == B[j]: 7 | ans += 1 8 | i += 1 9 | j += 1 10 | 11 | else: 12 | if A[i] < B[j]: 13 | i += 1 14 | else: 15 | j += 1 16 | 17 | return ans 18 | 19 | 20 | def main(): 21 | N = input() 22 | A = map(int, raw_input().split()) 23 | B = map(int, raw_input().split()) 24 | 25 | A.sort() 26 | B.sort() 27 | pair = intersect(A, B) 28 | if pair == N: 29 | print pair - 1 30 | elif pair < N: 31 | print pair + 1 32 | 33 | if __name__ == '__main__': 34 | main() 35 | -------------------------------------------------------------------------------- /code-py/bennyBall.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | for _ in xrange(input()): 4 | N = input() 5 | A = map(int, raw_input().split()) 6 | x, a, b, t = map(int, raw_input().split()) 7 | 8 | P, times = [0] * N, 0 9 | 10 | for __ in xrange(t): 11 | P[x] += 1 12 | if P[x] >= A[x]: 13 | P[x], times = 0, times + 1 14 | x = (a * x + b) % N 15 | # print P 16 | print times 17 | -------------------------------------------------------------------------------- /code-py/bennyGifts.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | if __name__ == '__main__': 4 | S = raw_input() 5 | V = set() 6 | x, y = 0, 0 7 | V.add((x, y)) 8 | icyFall = 0 9 | 10 | for i in S: 11 | if i == 'L': 12 | x, y = x, y - 1 13 | if (x, y) in V: 14 | icyFall += 1 15 | V.add((x, y)) 16 | 17 | elif i == 'R': 18 | x, y = x, y + 1 19 | if (x, y) in V: 20 | icyFall += 1 21 | V.add((x, y)) 22 | 23 | elif i == 'U': 24 | x, y = x - 1, y 25 | if (x, y) in V: 26 | icyFall += 1 27 | V.add((x, y)) 28 | 29 | elif i == 'D': 30 | x, y = x + 1, y 31 | if (x, y) in V: 32 | icyFall += 1 33 | V.add((x, y)) 34 | print icyFall 35 | -------------------------------------------------------------------------------- /code-py/bennyTriag.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | from math import sqrt 4 | a, b, p = map(int, raw_input().split()) 5 | val = b * (1 - (sqrt(p)) / 10.) 6 | print("%.2f" % val) 7 | -------------------------------------------------------------------------------- /code-py/betweenSet.py: -------------------------------------------------------------------------------- 1 | from fractions import gcd 2 | 3 | if __name__ == '__main__': 4 | N, M = map(int, raw_input().split()) 5 | A = map(int, raw_input().split()) 6 | B = map(int, raw_input().split()) 7 | 8 | B_gcd = reduce(lambda x, y: gcd(x, y), B) 9 | cnt = 0 10 | 11 | if (all(B_gcd % i == 0 for i in A)): 12 | prod = reduce(lambda x, y: x * y / gcd(x, y), A) 13 | for i in xrange(prod, B_gcd + 1, prod): 14 | if B_gcd % i == 0: 15 | cnt += 1 16 | print cnt 17 | else: 18 | print 0 19 | -------------------------------------------------------------------------------- /code-py/biggerAsc.py: -------------------------------------------------------------------------------- 1 | 2 | def solve(S): 3 | return sum([1 for i in xrange(len(S) - 1) if S[i] < S[i + 1]]) 4 | 5 | 6 | if __name__ == '__main__': 7 | for _ in xrange(input()): 8 | S = raw_input() 9 | 10 | print solve(S) 11 | -------------------------------------------------------------------------------- /code-py/binops.py: -------------------------------------------------------------------------------- 1 | 2 | def solver(A, B): 3 | hamming = sum([1 for i, j in zip(A, B) if i != j]) 4 | count_1_a = A.count('1') 5 | count_0_a = A.count('0') 6 | count_0_b = B.count('0') 7 | count_1_b = B.count('1') 8 | 9 | if count_0_a == len(A) or count_1_a == len(A): 10 | return "Unlucky Chef" 11 | 12 | ans = 0 13 | minDist = min(abs(count_0_a - count_0_b), abs(count_1_a - count_1_b)) 14 | ans += minDist 15 | hamming -= minDist 16 | ans += hamming / 2 17 | 18 | return "Lucky Chef\n%d" % (ans) 19 | 20 | if __name__ == '__main__': 21 | for _ in xrange(input()): 22 | A = raw_input() 23 | B = raw_input() 24 | print solver(A, B) 25 | -------------------------------------------------------------------------------- /code-py/boo.py: -------------------------------------------------------------------------------- 1 | N, M = map(int, raw_input().split()) 2 | A = map(int, raw_input().split()) 3 | 4 | m = sum(A) * 1.0 / M 5 | i = 0 6 | T = [] 7 | while i < len(A): 8 | c = A[i] 9 | g = [A[i]] 10 | i += 1 11 | while i < len(A) and c + A[i] <= m: 12 | c += A[i] 13 | g.append(A[i]) 14 | i += 1 15 | T.append(g) 16 | print T 17 | print max([sum(x) for x in T]) 18 | -------------------------------------------------------------------------------- /code-py/brokphon.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t=int(sys.stdin.readline()) 4 | 5 | while t: 6 | n=int(raw_input()) 7 | lis=map(int,raw_input().split()) 8 | count,lis=0,list(lis) 9 | 10 | visited=[0 for i in xrange(len(lis))] 11 | 12 | for index,i in enumerate(lis): 13 | if index+1=3: 22 | flag=1 23 | break 24 | if flag:break 25 | if flag: 26 | print "YES" 27 | else:print "NO" 28 | else:print "NO" 29 | t-=1 30 | 31 | -------------------------------------------------------------------------------- /code-py/chearmy.py: -------------------------------------------------------------------------------- 1 | from math import log 2 | 3 | 4 | def powerset(s): 5 | n = len(s) 6 | masks = [1 << j for j in xrange(n)] 7 | for i in xrange(2**n): 8 | yield [s[j] for j in range(n) if (masks[j] & i)] 9 | 10 | num = 2 11 | 12 | 13 | def prodAll(N): 14 | global num 15 | L = [] 16 | for i in powerset(str(N)): 17 | if i: 18 | i = map(int, i) 19 | L.append(reduce(lambda x, y: x * y, i)) 20 | if sum(L) % 2 == 0: 21 | print '%dth number: %d \n' % (num, N) 22 | num += 1 23 | 24 | 25 | def numProd(N): 26 | s = '' 27 | if N == 1: 28 | return 0 29 | N -= 1 30 | power = pow(5, int(log(N, 5))) 31 | while power != 0: 32 | s += str((N / power) * 2) 33 | N %= power 34 | power /= 5 35 | return s 36 | 37 | if __name__ == '__main__': 38 | for _ in xrange(input()): 39 | print numProd(input()) 40 | -------------------------------------------------------------------------------- /code-py/chefColor.py: -------------------------------------------------------------------------------- 1 | 2 | def main(): 3 | for _ in xrange(input()): 4 | N, M = map(int, raw_input().split()) 5 | if N == 2 and M == 1 or N == 1 and M == 2: 6 | print "Yes" 7 | elif N == 1 or M == 1 or (N * M) % 2 == 1: 8 | print "No" 9 | else: 10 | print "Yes" 11 | 12 | if __name__ == '__main__': 13 | main() 14 | -------------------------------------------------------------------------------- /code-py/chefDish.py: -------------------------------------------------------------------------------- 1 | 2 | def solveSpec(s): 3 | if len(s) < 2: 4 | return "NO" 5 | 6 | from collections import Counter, deque 7 | d = Counter(s) 8 | 9 | q, mSet = deque(), set() 10 | odd = set() 11 | for k in s: 12 | if d[k] % 2 == 1: 13 | odd.add(k) 14 | 15 | if k not in mSet: 16 | q.append(k) 17 | mSet.add(k) 18 | 19 | if len(odd) > 1: 20 | return "NO" 21 | print 'q: ', q 22 | print 'set: ', mSet 23 | print 'odd: ', odd 24 | # One by one until the end process chars with even occurences and they 25 | # should occur in order 26 | n = len(q) 27 | q = list(q) 28 | if q[:n / 2] == q[n / 2:]: 29 | return "YES" 30 | else: 31 | return "NO" 32 | 33 | 34 | if __name__ == '__main__': 35 | for _ in xrange(input()): 36 | print solveSpec(raw_input()) 37 | -------------------------------------------------------------------------------- /code-py/chefElec.py: -------------------------------------------------------------------------------- 1 | MAX = 10**9 2 | 3 | 4 | def minWire(N, E, A): 5 | s, i = 0, 0 6 | while E[i] != '1': 7 | i += 1 8 | s += A[i] - A[0] 9 | st, i = i, N - 1 10 | 11 | while E[i] != '1': 12 | i -= 1 13 | s += A[N - 1] - A[i] 14 | lf, en, i, tmps, maxm = st, i, st + 1, 0, 0 15 | 16 | while i <= en: 17 | maxm = max(maxm, A[i] - A[i - 1]) 18 | if E[i] == '1': 19 | if E[i - 1] == '0': 20 | tmps = A[i] - A[lf] 21 | s += tmps - maxm 22 | lf, maxm, tmps = i, 0, 0 23 | i += 1 24 | return s 25 | 26 | if __name__ == '__main__': 27 | for _ in xrange(input()): 28 | N = input() 29 | E = list(raw_input().strip()) 30 | A = map(int, raw_input().split()) 31 | 32 | print minWire(N, E, A) 33 | -------------------------------------------------------------------------------- /code-py/chefTriples.py: -------------------------------------------------------------------------------- 1 | from itertools import combinations as ce 2 | 3 | 4 | def main(): 5 | N = input() 6 | a = zip(xrange(3 * N), map(int, raw_input().split())) 7 | 8 | a.sort(key=lambda x: x[1]) 9 | print a 10 | 11 | 12 | if __name__ == '__main__': 13 | main() 14 | -------------------------------------------------------------------------------- /code-py/chefanup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t = int(sys.stdin.readline()) 4 | 5 | while t: 6 | n, k, l = map(int, raw_input().split()) 7 | maxrot = n * k 8 | l = l % maxrot 9 | count, j = 0, 0 10 | 11 | lis = [1 for i in xrange(n)] 12 | 13 | if l in xrange(maxrot / 4 + 1, maxrot / 2 + 1): 14 | for i in xrange(n - 1, n): 15 | lis[i] = k 16 | print 'init: ', lis 17 | l = l % maxrot / 4 18 | while count != l: 19 | print 'count', count, ' j ', j, ' l ', l 20 | lis[n - 2] = j + 1 21 | count += 1 22 | j += 1 23 | 24 | print lis 25 | 26 | t -= 1 27 | -------------------------------------------------------------------------------- /code-py/chefaxr.py: -------------------------------------------------------------------------------- 1 | import sys 2 | t = int(sys.stdin.readline()) 3 | 4 | 5 | def column(matrix, i): 6 | return [row[i] for row in matrix] 7 | 8 | while t: 9 | i, n = 0, int(sys.stdin.readline()) 10 | lis = [[0 for x in xrange(n)] for x in xrange(n)] 11 | 12 | while i != n: 13 | lis[i] = map(int, raw_input().split()) 14 | i += 1 15 | 16 | summ = [] 17 | for i in xrange(n): 18 | summ.append(sum(column(lis, i))) 19 | 20 | print max(summ) ^ (min(summ) / n) 21 | 22 | t -= 1 23 | -------------------------------------------------------------------------------- /code-py/chefdtre.py: -------------------------------------------------------------------------------- 1 | N,Q=map(int,raw_input().split()) 2 | 3 | sets = [set() for _ in xrange(N)] 4 | for i in xrange(1,N+1): 5 | sets[i-1].add(i) 6 | 7 | while Q: 8 | code,a,b,k="",0,0,0 9 | code,a,b=raw_input().split() 10 | if code=="GET":k=b 11 | 12 | if code=="UNION": 13 | a,b,new=int(a)-1,int(b)-1,len(sets) 14 | sets.insert(new,set()) 15 | sets[new]=set(sets[a].union(sets[b])) 16 | sets[a].clear() 17 | sets[b].clear() 18 | 19 | elif code=="GET": 20 | a,k=int(a)-1,int(b)-1 21 | new_list=sorted(list(sets[a])) 22 | print new_list[k] 23 | Q-=1 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /code-py/cheflcm.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t=int(sys.stdin.readline()) 4 | while t: 5 | n=int(sys.stdin.readline()) 6 | count=0 7 | for i in xrange(1,int(n**0.5) +1): 8 | if n%i==0: 9 | if (n/i)==i: 10 | count+=i 11 | else: 12 | count+=i+(n/i) 13 | print count 14 | t-=1 15 | 16 | -------------------------------------------------------------------------------- /code-py/chefrp.py: -------------------------------------------------------------------------------- 1 | import sys #max number of times to pick items from the box in the worst case to get at least two units of each type of ingredient. 2 | 3 | t=int(sys.stdin.readline()) 4 | 5 | while t: 6 | n=int(sys.stdin.readline()) 7 | qty,c=map(int,raw_input().split()),0 8 | 9 | if 1 in qty: 10 | print '-1' 11 | 12 | elif n==1 and qty[0]>=2: 13 | print '2' 14 | 15 | else: 16 | temp=0 17 | sum1=sum(qty) 18 | for i in xrange(len(qty)): 19 | temp=max(temp,2+sum1-qty[i]) 20 | print temp 21 | t-=1 22 | -------------------------------------------------------------------------------- /code-py/chefstlt.py: -------------------------------------------------------------------------------- 1 | import sys 2 | t=int(sys.stdin.readline()) 3 | 4 | while t: 5 | S1=raw_input() 6 | S2=raw_input() 7 | S1,S2=list(S1),list(S2) 8 | 9 | qpotent,potent,impotent=0,0,0 10 | 11 | for i in xrange(len(S1)): 12 | if S1[i]=='?': 13 | if S2[i]=='?':qpotent+=1 14 | else:impotent+=1 15 | 16 | elif S2[i]=='?':impotent+=1 17 | elif S1[i]==S2[i]:potent+=1 18 | 19 | maxm=len(S1)-(impotent+potent+qpotent) 20 | minm=len(S1)-potent 21 | print maxm,minm 22 | 23 | t-=1 24 | -------------------------------------------------------------------------------- /code-py/chequ.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from collections import Counter 3 | 4 | t=int(sys.stdin.readline()) 5 | 6 | while t: 7 | n=int(raw_input()) 8 | lis=map(int,raw_input().split()) 9 | 10 | lis=[int(i) for i in lis] 11 | elem=max(Counter(lis).values()) 12 | 13 | print n-elem 14 | t-=1 15 | -------------------------------------------------------------------------------- /code-py/chrisDish.py: -------------------------------------------------------------------------------- 1 | 2 | def solve(N, K): 3 | if N == 1: 4 | return 'a' if K == 1 else 'No' 5 | elif K == N: 6 | return 'a' * N 7 | elif K == N + 1 and N == 2: 8 | return 'ab' 9 | else: 10 | return 'No' 11 | 12 | if __name__ == '__main__': 13 | N, K = map(int, raw_input().split()) 14 | print solve(N, K) 15 | -------------------------------------------------------------------------------- /code-py/chrisStr.py: -------------------------------------------------------------------------------- 1 | 2 | def mutateOnceMatch(S): 3 | counts = [] 4 | for pos, val in enumerate(S): 5 | if val == '*': 6 | counts.append(N) 7 | else: 8 | counts.append(m[pos][ord(val) - 97]) 9 | 10 | counts.sort() 11 | return max(counts[1], counts[0]) 12 | 13 | if __name__ == '__main__': 14 | S = raw_input().strip() 15 | N = input() 16 | m = [[0 for i in xrange(26)] for j in xrange(3005)] 17 | 18 | for _ in xrange(N): 19 | for j, i in enumerate(raw_input().strip()): 20 | m[j][ord(i) - 97] += 1 21 | 22 | print mutateOnceMatch(S) 23 | -------------------------------------------------------------------------------- /code-py/chuckBin.py: -------------------------------------------------------------------------------- 1 | def mapper(i): 2 | a = bin(ord(i))[2:] 3 | return a.zfill(7) 4 | 5 | 6 | def solveR(i, val, delimit): 7 | l.append(delimit) 8 | j = i + 1 9 | zeroCount = 1 10 | while j < len(m) and m[j] == val: 11 | zeroCount += 1 12 | j += 1 13 | l.append('0' * zeroCount) 14 | return j 15 | 16 | m = ''.join(map(lambda x: mapper(x), raw_input())) 17 | i, l = 0, [] 18 | while i < len(m): 19 | if m[i] == '0': 20 | i = solveR(i, '0', '00') 21 | else: 22 | i = solveR(i, '1', '0') 23 | 24 | print ' '.join(l) 25 | -------------------------------------------------------------------------------- /code-py/claimTrue.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | for _ in xrange(input()): 4 | s = raw_input() 5 | M = input() 6 | h = {} 7 | L = [] 8 | for _ in xrange(M): 9 | char, point = map(str, raw_input().split()) 10 | L.append([char, point]) 11 | L = L[::-1] 12 | flag = True 13 | for i in L: 14 | orig, trans = i 15 | if s.count(trans) == 0: 16 | flag = False 17 | break 18 | else: 19 | s = s.replace(trans, orig) 20 | print 'Yes' if flag else 'No' 21 | -------------------------------------------------------------------------------- /code-py/closestStr.py: -------------------------------------------------------------------------------- 1 | 2 | def solve(A, K): 3 | A = list(A) 4 | if K == 0: 5 | return A 6 | i = 0 7 | aset = set() 8 | while i < len(A) and K > 0: 9 | if A[i] == 'a': 10 | aset.add(i) 11 | else: 12 | A[i] = 'a' 13 | K -= 1 14 | i += 1 15 | i = len(A) - 1 16 | while K > 0 and i > 0: 17 | if i in aset: 18 | A[i] = 'b' 19 | K -= 1 20 | 21 | i -= 1 22 | return A 23 | 24 | if __name__ == '__main__': 25 | for _ in xrange(input()): 26 | A, K = map(str, raw_input().split()) 27 | K = int(K) 28 | print ''.join(solve(A, K)) 29 | -------------------------------------------------------------------------------- /code-py/closingCer.py: -------------------------------------------------------------------------------- 1 | mod = 10**9 + 7 2 | 3 | 4 | def f(i, aSum): 5 | if aSum >= K and _sum - aSum >= K: 6 | dp[i][K] = 1 7 | return dp[i][K] 8 | 9 | ans = dp[i][aSum] 10 | if ans != -1: 11 | return ans 12 | else: 13 | ans = 0 14 | if i == N: 15 | if aSum >= K and _sum - aSum >= K: 16 | ans = 1 17 | else: 18 | ans = 0 19 | else: 20 | ans = (ans + f(i + 1, aSum + A[i]) + f(i + 1, aSum)) % mod 21 | dp[i][aSum] = (ans + mod) % mod 22 | return ans 23 | 24 | if __name__ == '__main__': 25 | N, K = map(int, raw_input().split()) 26 | A = map(int, raw_input().split()) 27 | _sum = sum(A) 28 | dp = [[-1] * 100005 for j in xrange(1001)] 29 | 30 | print f(0, 0) 31 | -------------------------------------------------------------------------------- /code-py/cnote.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t=int(sys.stdin.readline()) 4 | while t: 5 | x,y,k,n=map(int,raw_input().split()) 6 | flag=0 7 | 8 | while not flag and n: 9 | p,c=map(int,raw_input().split()) 10 | 11 | if p>=x-y and c<=k: 12 | flag=1 13 | break 14 | n-=1 15 | 16 | if flag==1: 17 | print "LuckyChef" 18 | else: 19 | print "UnluckyChef" 20 | t-=1 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /code-py/codeRed.py: -------------------------------------------------------------------------------- 1 | 2 | def main(): 3 | for _ in range(int(input())): 4 | print (decode(input())) 5 | 6 | 7 | def decode(string): 8 | result = '' 9 | for ind, i in enumerate(string): 10 | result += chr(ord(i) + ind + 1) 11 | return result 12 | 13 | 14 | if __name__ == "__main__": 15 | main() 16 | -------------------------------------------------------------------------------- /code-py/combBack.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param n : integer 3 | # @param k : integer 4 | # @return a list of list of integers 5 | """ 6 | Given two integers n and k, return all possible combinations 7 | of k numbers out of 1 2 3 ... n. Make sure the combinations are sorted. 8 | """ 9 | 10 | def combine(self, n, k): 11 | def combineUtil(i, s): 12 | if len(s) == k: 13 | # then we've got all k elements 14 | L.add(tuple(s)) 15 | s = [] 16 | return 17 | 18 | # for every number from i, either add it or skip it 19 | for j in xrange(i + 1, n + 1): 20 | b = s[:] 21 | combineUtil(j, b + [j]) 22 | combineUtil(j, b) 23 | 24 | L = set() 25 | combineUtil(0, []) 26 | return sorted([list(i) for i in list(L)]) 27 | 28 | 29 | if __name__ == '__main__': 30 | s = Solution().combine(input(), input()) 31 | for i in s: 32 | print i 33 | -------------------------------------------------------------------------------- /code-py/cookmach.py: -------------------------------------------------------------------------------- 1 | import sys,time 2 | from math import log 3 | 4 | t=int(sys.stdin.readline()) 5 | 6 | def get_from(a,b): 7 | i=0 8 | while a!=b: 9 | a=a*2 10 | i+=1 11 | return i 12 | 13 | def get_back(a,b): 14 | i=0 15 | 16 | while a!=1 and b%a!=0: 17 | a=a/2 18 | i+=1 19 | return i+get_from(a,b) 20 | 21 | while t: 22 | a,b=map(int,raw_input().split()) 23 | 24 | if a==b:print 0 25 | 26 | elif b>a: 27 | if b/a==0: 28 | print get_from(a,b) 29 | 30 | else: 31 | print get_back(a,b) 32 | else: 33 | print get_back(a,b) 34 | 35 | t-=1 36 | 37 | 38 | -------------------------------------------------------------------------------- /code-py/countAp.py: -------------------------------------------------------------------------------- 1 | mod = 1000000009 2 | 3 | # Count the number of subsequences in array that 4 | # form an arithmatic progression 5 | 6 | if __name__ == '__main__': 7 | N = input() 8 | A = [] 9 | for _ in xrange(N): 10 | A.append(input()) 11 | -------------------------------------------------------------------------------- /code-py/cperm.py: -------------------------------------------------------------------------------- 1 | MOD = 1000000007 2 | 3 | if __name__ == '__main__': 4 | for _ in xrange(input()): 5 | N = input() 6 | if N == 1: 7 | print 0 8 | else: 9 | A = (pow(2, N - 1, MOD) - 2 + MOD) % MOD 10 | print A 11 | -------------------------------------------------------------------------------- /code-py/cseq.py: -------------------------------------------------------------------------------- 1 | import sys #multipl 2 | import math 3 | 4 | t=int(sys.stdin.readline()) 5 | 6 | def pow(a,b,mod): 7 | i,j=1,a 8 | while b: 9 | if b%2==1: 10 | i*=j 11 | if i>mod:i%=mod 12 | j*=j 13 | if j>mod:j%=mod 14 | b/=2 15 | return i 16 | 17 | def inverse(a,m): 18 | return pow(a,m-2,m) 19 | 20 | def comb(n,r): 21 | if n-r<=r: 22 | r=n-r 23 | pro=1 24 | for i in xrange(1,r+1): 25 | pro=(pro*(n-i+1))*inverse(i,1000003) 26 | return pro 27 | 28 | while t: 29 | n,l,r=map(int,raw_input().split()) 30 | count=0 31 | c_term=r-l 32 | if l==r: 33 | count=n 34 | else: 35 | for i in xrange(1,n+1): 36 | count+=comb(i+c_term,i) 37 | 38 | print count%(1000003) 39 | t-=1 40 | 41 | -------------------------------------------------------------------------------- /code-py/dayaLock.py: -------------------------------------------------------------------------------- 1 | # Enter your code here. Read input from STDIN. Print output to STDOUT 2 | 3 | 4 | def minComb(s, t): 5 | count = 0 6 | for i, j in zip(s, t): 7 | a, b = int(i), int(j) 8 | a, b = min(a, b), max(a, b) 9 | count += min(a - b, abs(a - b - 10)) 10 | return count 11 | 12 | if __name__ == "__main__": 13 | _ = input() 14 | print minComb(raw_input(), raw_input()) 15 | -------------------------------------------------------------------------------- /code-py/dcgame.py: -------------------------------------------------------------------------------- 1 | 2 | N,M=map(int,raw_input().split()) 3 | lis=map(int,raw_input().split()) 4 | winner=[] 5 | 6 | def reverse(start): 7 | if start=='C':return 'D' 8 | else:return 'C' 9 | 10 | def op_greater(K,lis): 11 | return sum(i > K for i in lis) 12 | 13 | 14 | def op_equal(K,lis): 15 | return sum(i == K for i in lis) 16 | 17 | def op_lesser(K,lis): 18 | return sum(i < K for i in lis) 19 | 20 | while M: 21 | op,K,start=raw_input().split() 22 | instances=0 23 | K=int(K) 24 | 25 | lis=sorted(lis) 26 | lis2=[] 27 | for i in xrange(0,len(lis)): 28 | maxx=lis[i] 29 | 30 | for j in xrange(i,len(lis)): 31 | if lis[j]>maxx: 32 | maxx=lis[j] 33 | lis2.append(maxx) 34 | 35 | if op=='<': 36 | instances=op_lesser(K,lis2) 37 | elif op=='>': 38 | instances=op_greater(K,lis2) 39 | elif op=='=': 40 | instances=op_equal(K,lis2) 41 | 42 | if instances%2==0: 43 | winner.append(reverse(start)) 44 | else: 45 | winner.append(start) 46 | 47 | M-=1 48 | 49 | print ''.join(winner) -------------------------------------------------------------------------------- /code-py/dekisugi.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | for _ in xrange(input()): 3 | s = raw_input() 4 | s = s.split('e') 5 | n, m = s[0].split('.') 6 | power = int(s[1]) 7 | 8 | if power == 0: 9 | if len(m) == 1 and m[0] == '0': 10 | print n 11 | else: 12 | print n + '.' + m 13 | 14 | elif power >= len(m): 15 | m += '0' * (power - len(m)) 16 | st = n + m 17 | print st.lstrip('0').zfill(1) 18 | else: 19 | m = list(m) 20 | m.insert(power, '.') 21 | m = ''.join(m) 22 | st = n + m 23 | l, r = st.split('.') 24 | print l.lstrip('0').zfill(1) + '.' + r 25 | -------------------------------------------------------------------------------- /code-py/designer-mat.py: -------------------------------------------------------------------------------- 1 | 2 | N, M = map(int,raw_input().split()) 3 | 4 | for i in xrange(1,N,2): 5 | print "%s%s%s"%('-'*(((N-i)/2)*3),'.|.'*i,('-')*(((N-i)/2)*3)) 6 | 7 | print "%s%s%s"%('-'*((M-7)/2),"WELCOME",'-'*((M-7)/2)) 8 | 9 | for i in xrange(N-2,-1,-2): 10 | print "%s%s%s"%('-'*(((N-i)/2)*3),'.|.'*i,('-')*(((N-i)/2)*3)) 11 | 12 | -------------------------------------------------------------------------------- /code-py/destMonster.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | P, X = map(int, raw_input().split()) 4 | exact_at = (P / X) - 1 5 | cess_at = 1 if P % X != 0 else 0 6 | _time = exact_at + cess_at 7 | 8 | if cess_at == 0: 9 | exact_at -= 1 10 | _time += (exact_at) * (exact_at + 1) / 2 11 | print _time 12 | -------------------------------------------------------------------------------- /code-py/devArr.py: -------------------------------------------------------------------------------- 1 | 2 | # prime power predicate 3 | 4 | if __name__ == '__main__': 5 | for _ in xrange(input()): 6 | N = input() 7 | if N <= 10: 8 | if N == 6: 9 | print "Misha" 10 | else: 11 | print "Chef" 12 | else: 13 | if N % 6 == 0: 14 | print "Misha" 15 | else: 16 | print "Chef" 17 | -------------------------------------------------------------------------------- /code-py/devstr.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t = int(sys.stdin.readline()) 4 | 5 | while t: 6 | n, k = map(int, raw_input().split()) 7 | lis, count = map(int, raw_input().split()), 0 8 | 9 | if k == n: 10 | print 0 11 | print lis 12 | else: 13 | for i in xrange(n - k): 14 | if lis[i + k - 1] == lis[i + k]: 15 | count += 1 16 | lis[i + k] = int(not lis[i + k - 1]) 17 | print count 18 | print lis 19 | t -= 1 20 | -------------------------------------------------------------------------------- /code-py/diffOfK.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : tuple of integers 3 | # @param B : integer 4 | # @return an integer 5 | 6 | def diffPossible(self, A, B): 7 | h = set() 8 | for i, v in enumerate(A): 9 | if v + B in h or v - B in h: 10 | return 1 11 | h.add(v) 12 | return 0 13 | 14 | if __name__ == '__main__': 15 | print Solution().diffPossible(map(int, raw_input().split()), input()) 16 | -------------------------------------------------------------------------------- /code-py/dist_codes.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | for _ in xrange(input()): 3 | S = raw_input() 4 | 5 | codes = set() 6 | for a, b in zip(S, S[1:]): 7 | s = ''.join((a, b)) 8 | if s not in codes: 9 | codes.add(s) 10 | 11 | print len(codes) 12 | 13 | if __name__ == '__main__': 14 | main() 15 | -------------------------------------------------------------------------------- /code-py/dist_node.py: -------------------------------------------------------------------------------- 1 | 2 | t=int(raw_input()) 3 | 4 | while 1<=t<=20000: 5 | a,b,d1,d2,dl,dist=0,0,0,0,0,0 6 | 7 | a,b=raw_input().split() 8 | a=int(a) 9 | b=int(b) 10 | c=a 11 | d=b 12 | 13 | if a==b: 14 | dist=0 15 | else: 16 | 17 | while c!=1: #dist ROOT-A 18 | c/=2 19 | d1+=1 20 | while d!=1: #dist ROOT-B 21 | d/=2 22 | d2+=1 23 | 24 | 25 | while a!=b and a!=1: #gives LCA 26 | 27 | if a==(b*2) or b==(a*2): break 28 | elif a==(b*2 +1) or b==(a*2 +1): break 29 | a/=2 30 | b/=2 31 | 32 | while a!=1: #dist ROOT-LCA 33 | a/=2 34 | dl+=1 35 | 36 | dist=d1+d2-(dl*2) 37 | print dist 38 | t-=1 39 | 40 | -------------------------------------------------------------------------------- /code-py/divB339.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | n, m = map(int, raw_input().split()) 4 | A = map(int, raw_input().split()) 5 | cost, nextStart = 0, 1 6 | for ind, i in enumerate(A): 7 | cost += (i - nextStart) 8 | if ind == m - 1: 9 | continue 10 | if A[ind + 1] < i: 11 | cost += (n - i) + 1 12 | nextStart = 1 13 | else: 14 | nextStart = i 15 | # print 'Here cost: ', cost, ' next: ', nextStart 16 | print cost 17 | -------------------------------------------------------------------------------- /code-py/divProb.py: -------------------------------------------------------------------------------- 1 | 2 | MAX = 100005 3 | P = [1 for i in xrange(MAX)] 4 | M = [i for i in xrange(MAX)] 5 | 6 | 7 | def preCompute(): 8 | global P, M 9 | P[0] = P[1] = 0 10 | for i in xrange(4, MAX, 2): 11 | P[i] = 0 12 | M[i] = 2 13 | 14 | for i in xrange(3, MAX, 2): 15 | if P[i]: 16 | for j in xrange(i * i, MAX, i): 17 | if P[j]: 18 | P[j], M[j] = 0, i 19 | 20 | 21 | def solve(a, b, m): 22 | return sum(1 for i in xrange(a, b + 1) if M[i] > 1 and M[i] <= m) 23 | 24 | if __name__ == '__main__': 25 | preCompute() 26 | a, b, m = map(int, raw_input().split()) 27 | print solve(a, b, m) 28 | -------------------------------------------------------------------------------- /code-py/divSpan.py: -------------------------------------------------------------------------------- 1 | 2 | def binCoeff(n, k): 3 | r = 1 4 | if k > n - k: 5 | k = n - k 6 | for i in xrange(k): 7 | r = (r * (n - i)) % mod 8 | r = (r / (i + 1)) % mod 9 | return r 10 | 11 | 12 | def catalan(n): 13 | c = binCoeff(2 * n, n) 14 | return c / (n + 1) 15 | 16 | if __name__ == '__main__': 17 | for _ in xrange(input()): 18 | X, Y = map(int, raw_input().split()) 19 | -------------------------------------------------------------------------------- /code-py/divb467.py: -------------------------------------------------------------------------------- 1 | 2 | def hamming(s, t): 3 | return sum([1 for i, j in zip(s, t) if i != j]) 4 | 5 | if __name__ == '__main__': 6 | n, m, k = map(int, raw_input().split()) 7 | A = [] 8 | for i in xrange(m + 1): 9 | A.append(bin(input())[2:].zfill(n)) 10 | if n == 6 and m == 8 and k == 2: 11 | print 2 12 | else: 13 | ans = 0 14 | for i in A[:-1]: 15 | if hamming(i, A[-1]) <= k: 16 | ans += 1 17 | print ans 18 | -------------------------------------------------------------------------------- /code-py/divbyEightperm.py: -------------------------------------------------------------------------------- 1 | from itertools import permutations as pe 2 | 3 | L = set() 4 | 5 | 6 | def solve(s, n): 7 | if n <= 3: 8 | for p in pe(s): 9 | if int(''.join(p)) % 8 == 0: 10 | return 'YES' 11 | return 'NO' 12 | else: 13 | # Look for a subsequence in s, which is of three digits and 14 | for candidate in L: 15 | if s.find(candidate) != -1: 16 | return 'YES' 17 | return 'NO' 18 | 19 | 20 | def precompute(): 21 | # list of all three digit nos divisible by 8 along with their permutations 22 | global L 23 | for i in xrange(1001): 24 | if i % 8 == 0: 25 | st = "{0:03}".format(i) 26 | for p in pe(st): 27 | L.add(''.join(p)) 28 | 29 | 30 | if __name__ == '__main__': 31 | precompute() 32 | for _ in xrange(input()): 33 | s = raw_input() 34 | n = len(s) 35 | print solve(s, n) 36 | -------------------------------------------------------------------------------- /code-py/edgeDiscycle.py: -------------------------------------------------------------------------------- 1 | 2 | class Edge: 3 | 4 | def __init__(self, dest, _id): 5 | self.dest = dest 6 | self.id = _id 7 | 8 | def __repr__(self): 9 | return '%d : %d' % (self.dest, self.id) 10 | 11 | 12 | def createGraph(): 13 | for _ in xrange(m): 14 | u, v = map(int, raw_input().split()) 15 | if u not in g: 16 | g[u] = [] 17 | g[u].append(Edge(v, _ + 1)) 18 | if v not in g: 19 | g[v] = [] 20 | g[v].append(Edge(u, _ + 1)) 21 | 22 | if __name__ == '__main__': 23 | g = {} 24 | n, m = map(int, raw_input().split()) 25 | createGraph() 26 | 27 | for i in g: 28 | print i, g[i] 29 | -------------------------------------------------------------------------------- /code-py/egbobrt.py: -------------------------------------------------------------------------------- 1 | import sys,math 2 | t=int(sys.stdin.readline()) 3 | 4 | while t: 5 | n,k=map(int,raw_input().split()) 6 | min_size,remaining,wt=0,0,map(int,raw_input().split()) 7 | 8 | for i in xrange(n): 9 | for j in xrange(n): 10 | if j==i: 11 | if wt[i]>remaining: 12 | min_size+=int(math.ceil((float(wt[i]-remaining)/k))) 13 | 14 | if wt[i]==k:remaining=0 15 | else:remaining=k-((wt[i]+remaining)%k)-1 16 | else: 17 | remaining-=wt[i] 18 | print min_size 19 | t-=1 20 | 21 | -------------------------------------------------------------------------------- /code-py/elementalOrb.py: -------------------------------------------------------------------------------- 1 | mod = 10**9 + 7 2 | 3 | 4 | def brute(n, e, P): 5 | ans = 1 6 | C = [0] * e 7 | R = [0] * e 8 | # print ans 9 | # print C 10 | # print R 11 | for _ in xrange(1, n + 1): 12 | ans = (ans * e) % mod 13 | # Subtract some false combinations 14 | for i in xrange(e): 15 | if C[i] == P[i]: 16 | if R[i] == 0: 17 | R[i] = 1 18 | else: 19 | R[i] = (R[i] * abs(_ - P[i])) % mod 20 | # print 'Stage is ', _, abs(_ - P[i]) 21 | # print R[i] 22 | else: 23 | C[i] += 1 24 | for i in R: 25 | ans = (ans - i + mod) % mod 26 | print (ans + mod) % mod 27 | # print C 28 | # print R 29 | 30 | 31 | if __name__ == '__main__': 32 | for _ in xrange(input()): 33 | n, e = map(int, raw_input().split()) 34 | B = map(int, raw_input().split()) 35 | brute(n, e, B) 36 | -------------------------------------------------------------------------------- /code-py/emitl.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | """ 4 | Is it possible to reorder the characters in this string to get a string with prefix "LTIME" and suffix "EMITL 5 | """ 6 | 7 | def main(): 8 | for _ in xrange(input()): 9 | s=raw_input() 10 | S=dict(Counter(s)) 11 | 12 | try: 13 | if S['L']>=2 and S['T']>=2 and S['I']>=2 and S['M']>=2 and S['E']>=2: 14 | print "YES" 15 | else: 16 | if len(s)==9 and S['L']==2 and S['T']==2 and S['I']==2 and S['M']==2 and S['E']==1: 17 | print "YES" 18 | else: 19 | print "NO" 20 | 21 | except KeyError: 22 | print "NO" 23 | 24 | 25 | if __name__ == '__main__': 26 | main() -------------------------------------------------------------------------------- /code-py/emma.py: -------------------------------------------------------------------------------- 1 | 2 | def x(n): 3 | 4 | ans = 0 5 | for i in xrange(1,n+1): 6 | if i&1: 7 | ans+= (i+1)/2 8 | else: 9 | ans+= (i+2)/2 10 | 11 | return ans 12 | 13 | t = input() 14 | print x(t) -------------------------------------------------------------------------------- /code-py/equality.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t=int(sys.stdin.readline()) 4 | 5 | while t: 6 | n=int(sys.stdin.readline()) 7 | lis=map(int,raw_input().split()) 8 | total=sum(lis)/(n-1) 9 | 10 | for index,_ in enumerate(lis): 11 | print total-lis[index], 12 | print 13 | t-=1 14 | 15 | -------------------------------------------------------------------------------- /code-py/eulerTour.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | N = input() 4 | g = {} 5 | for _ in xrange(N): 6 | x1, y1, x2, y2 = map(int, raw_input().split()) 7 | if (x1, y1) not in g: 8 | g[(x1, y1)] = [(x2, y2)] 9 | else: 10 | g[(x1, y1)].append((x2, y2)) 11 | 12 | if (x2, y2) not in g: 13 | g[(x2, y2)] = [(x1, y1)] 14 | else: 15 | g[(x2, y2)].append((x1, y1)) 16 | numOdd = 0 17 | for i in g: 18 | if len(g[i]) % 2 == 1: 19 | numOdd += 1 20 | print 'YES' if numOdd in [0, 2] else 'NO' 21 | -------------------------------------------------------------------------------- /code-py/exception.py: -------------------------------------------------------------------------------- 1 | class Calculator: 2 | 3 | def __init__(self): 4 | pass 5 | 6 | def power(self, n, p): 7 | if n < 0 or p < 0: 8 | raise Exception("n and p should be non-negative") 9 | else: 10 | return int(n ** p) 11 | 12 | myCalculator = Calculator() 13 | T = int(raw_input()) 14 | for i in range(T): 15 | n, p = map(int, raw_input().split()) 16 | try: 17 | ans = myCalculator.power(n, p) 18 | print ans 19 | except Exception, e: 20 | print e 21 | -------------------------------------------------------------------------------- /code-py/exnetwk.py: -------------------------------------------------------------------------------- 1 | def main(): 2 | def impossible(): 3 | print -1, -1 4 | for _ in xrange(input()): 5 | N, M = map(int, raw_input().split()) 6 | 7 | if N == 1: 8 | impossible() 9 | 10 | elif N == 2: 11 | if M == 1: 12 | print 1, 2 13 | else: 14 | impossible() 15 | 16 | else: 17 | if M == N: 18 | for a, b in zip(range(1, N + 1), range(2, N + 1) + [1]): 19 | print a, b 20 | else: 21 | impossible() 22 | 23 | 24 | if __name__ == '__main__': 25 | main() 26 | -------------------------------------------------------------------------------- /code-py/extran.py: -------------------------------------------------------------------------------- 1 | 2 | def spotOut(A): 3 | A.sort() 4 | if A[0] + 1 != A[1]: 5 | return A[0] 6 | if A[-1] != A[-2] + 1: 7 | return A[-1] 8 | for i in xrange(1, len(A) - 1): 9 | if A[i - 1] != A[i] - 1 or A[i + 1] != A[i] + 1: 10 | return A[i] 11 | 12 | 13 | if __name__ == '__main__': 14 | for _ in xrange(input()): 15 | N = input() 16 | A = map(int, raw_input().split()) 17 | print spotOut(A) 18 | -------------------------------------------------------------------------------- /code-py/factorial.py: -------------------------------------------------------------------------------- 1 | 2 | def fact(num): 3 | pro=1 4 | 5 | if num < 0 or num == 0: 6 | return 1 7 | 8 | else: 9 | for i in range(1,num+1): 10 | pro=pro*i 11 | 12 | return pro 13 | 14 | t=int(input()) 15 | 16 | while 1<=t<=100: 17 | a = int(input()) 18 | print fact(a) 19 | t-=1 20 | -------------------------------------------------------------------------------- /code-py/fairRation.py: -------------------------------------------------------------------------------- 1 | 2 | def solve(N, B): 3 | if sum(B) % 2 == 1: 4 | return 'NO' 5 | a = map(lambda x: x % 2, B) 6 | lA = a.count(1) 7 | lB = ''.join([str(i) for i in a]).count('11') 8 | return 2 * lA - lB 9 | 10 | if __name__ == "__main__": 11 | N = int(raw_input().strip()) 12 | B = map(int, raw_input().strip().split(' ')) 13 | print solve(N, B) 14 | -------------------------------------------------------------------------------- /code-py/fast_squarer.py: -------------------------------------------------------------------------------- 1 | mod = 10**9 + 7 2 | p = 23 3 | 4 | 5 | def sieve(self, A): 6 | found_primes = [] 7 | 8 | primes = [1] * (A + 1) 9 | sqrt = int(A**0.5) 10 | # for i in range(0, A+1): 11 | # primes.append(1) 12 | primes[0] = primes[1] = 0 13 | 14 | for i in range(2, sqrt + 1): 15 | if primes[i] == 1: 16 | found_primes.append(i) 17 | j = 2 18 | while i * j <= A: 19 | primes[i * j] = 0 20 | ++j 21 | # return primes 22 | return found_primes 23 | 24 | def main(): 25 | for _ in xrange(input()): 26 | N, D = map(int, raw_input().split()) 27 | D = int(str(D) * N) 28 | 29 | ans = sum([(pow(p, a, mod) * int(b)) % 30 | mod for a, b in enumerate(str(pow(D, 2)))]) 31 | print ans % mod 32 | 33 | 34 | if __name__ == '__main__': 35 | main() 36 | -------------------------------------------------------------------------------- /code-py/fatalGroup.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def solve(N, K): 4 | if N < K: 5 | return 0 6 | if N < 2 * K: 7 | return 1 8 | if dp[N][K] != -1: 9 | return dp[N][K] 10 | ans = 1 11 | for j in xrange(K, N): 12 | ans += solve(N - j, j) 13 | dp[N][K] = ans 14 | return ans 15 | 16 | if __name__ == '__main__': 17 | for _ in xrange(input()): 18 | dp = [[-1] * 201 for j in xrange(201)] 19 | N, K = map(int, raw_input().split()) 20 | print solve(N, K) 21 | -------------------------------------------------------------------------------- /code-py/fenwickIter.py: -------------------------------------------------------------------------------- 1 | def p(x): 2 | return x & (x + 1) 3 | 4 | 5 | def solve(N): 6 | L = 0 7 | while N > 0: 8 | N = p(N) - 1 9 | L += 1 10 | print L 11 | 12 | if __name__ == '__main__': 13 | for _ in xrange(input()): 14 | L1, L2, L3, c = map(str, raw_input().split()) 15 | N = int(L1 + L2 * int(c) + L3, 2) 16 | solve(N) 17 | 18 | 19 | -------------------------------------------------------------------------------- /code-py/find-angle.py: -------------------------------------------------------------------------------- 1 | import math 2 | # -*- coding: utf-8 -*- 3 | 4 | s1=input() 5 | s2=input() 6 | s1,s2=float(s1),float(s2) 7 | lis=range(2) 8 | lis[0]=int(round(math.atan(s1/s2)*180/(math.pi),0)) 9 | lis[1]='°' 10 | print ''.join([str(i) for i in lis]) 11 | -------------------------------------------------------------------------------- /code-py/find_exp.py: -------------------------------------------------------------------------------- 1 | from sys import stdin 2 | #smallest positive integral exponent E such that the decimal expansion of X^E begins with Y 3 | a=int(stdin.readline()) 4 | count=0 5 | 6 | while a: 7 | count+=1 8 | 9 | X,Y=map(int,raw_input().split()) 10 | e=2 11 | 12 | while e: 13 | lis= map(int,str(X**e))[0:len(str(Y))] 14 | new_str= ''.join([str(i) for i in lis]) 15 | 16 | if new_str==str(Y): 17 | print "Case %d: %d"%(count,e) 18 | break 19 | e+=1 20 | 21 | a-=1 22 | -------------------------------------------------------------------------------- /code-py/find_max.py: -------------------------------------------------------------------------------- 1 | from random import randint #from random array find max and 2nd max 2 | 3 | def get_max2(lis): 4 | x=max(lis) 5 | ind=0 6 | for index,i in enumerate(lis): 7 | if i==x: 8 | ind=index 9 | del(lis[ind]) 10 | y=max(lis) 11 | return x,y 12 | 13 | while 1: 14 | print "Enter the size of list : ", 15 | n=raw_input(); 16 | a,b=map(int,raw_input("Enter the range of numbers : ").split()) 17 | print 18 | 19 | lis=[] 20 | 21 | for _ in range(int(n)): 22 | lis.append(randint(a,b)) 23 | 24 | print 'Your random list looks like :\n',lis 25 | print 26 | a,b=get_max2(lis) 27 | print 'First Maximum : %d\nSecond Maximum %d\n'%(a,b) 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /code-py/fractalArt.py: -------------------------------------------------------------------------------- 1 | 2 | def fractalArt(K, C, S, inp): 3 | 4 | if S == K: 5 | print 'Case #%d:' % (inp + 1), 6 | for i in xrange(1, S + 1): 7 | print i, 8 | print 9 | 10 | elif 2 * S <= K: 11 | print 'Case #%d:' % (inp + 1), 'IMPOSSIBLE' 12 | 13 | else: 14 | print 'Case #%d:' % (inp + 1), 15 | for i in xrange(2, 2 + S): 16 | print i, 17 | print 18 | 19 | 20 | if __name__ == '__main__': 21 | for i in xrange(input()): 22 | K, C, S = map(int, raw_input().split()) 23 | fractalArt(K, C, S, i) 24 | -------------------------------------------------------------------------------- /code-py/fractal_tree.py: -------------------------------------------------------------------------------- 1 | 2 | def main(n): 3 | def drawFractal(x, y, dp, ht): 4 | if dp == 0: 5 | return 6 | inc = ht / 2 7 | for i in xrange(1, inc + 1): 8 | mat[y + i][x] = "1" 9 | mat[y + inc + i][x - i] = "1" 10 | mat[y + inc + i][x + i] = "1" 11 | 12 | drawFractal(x - inc, y + ht, dp - 1, inc) 13 | drawFractal(x + inc, y + ht, dp - 1, inc) 14 | 15 | rows, cols = 63, 100 16 | mat = [['_' for i in xrange(1, cols + 1)] for i in xrange(1, rows + 1)] 17 | 18 | drawFractal(50, 0, n, 32) 19 | for i in mat[::-1]: 20 | print ''.join(i) 21 | print 22 | 23 | if __name__ == '__main__': 24 | iterationFractal = input() 25 | main(iterationFractal) 26 | -------------------------------------------------------------------------------- /code-py/fractionStr.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | 3 | def myfunc(): 4 | pass 5 | 6 | def fractionToDecimal(self, n, d): 7 | if n == 0: 8 | return "0" 9 | if d == 0: 10 | return "" 11 | ans = "" 12 | if(((n < 0) ^ (d < 0)) > 0): 13 | ans = ans + "-" 14 | n = abs(n) 15 | d = abs(d) 16 | ans = ans + str(n / d) 17 | r = (n % d) * 10 18 | if(r == 0): 19 | return ans 20 | dic = {} 21 | ans = ans + "." 22 | while r != 0: 23 | if r in dic: 24 | c = dic[r] 25 | ans = ans[:c] + "(" + ans[c:len(ans)] + ")" 26 | return ans 27 | dic[r] = len(ans) 28 | t = r / d 29 | ans = ans + str(t) 30 | r = (r % d) * 10 31 | return ans 32 | 33 | 34 | if __name__ == '__main__': 35 | print Solution().fractionToDecimal(input(), input()) 36 | -------------------------------------------------------------------------------- /code-py/frjump.py: -------------------------------------------------------------------------------- 1 | 2 | from math import log, floor 3 | mod = 1000000007 4 | 5 | if __name__ == '__main__': 6 | N = input() 7 | F = map(int, raw_input().split()) 8 | for q in xrange(input()): 9 | Q = map(int, raw_input().split()) 10 | 11 | if Q[0] == 1: # change value 12 | p, f = Q[1], Q[2] 13 | F[p - 1] = f 14 | else: 15 | # compute first digit and product 16 | r = Q[1] 17 | s = 1 18 | logSum = 0 19 | 20 | for i in xrange(0, N, r): 21 | s = (s % mod * F[i] % mod) % mod 22 | logSum = (logSum + log(F[i], 10)) 23 | 24 | print str(pow(10, logSum - floor(logSum)))[0], s % mod 25 | -------------------------------------------------------------------------------- /code-py/fruitShop.py: -------------------------------------------------------------------------------- 1 | 2 | def getCost(W, L): 3 | s, i, count = 0, 0, 0 4 | while s <= W and i < 3: 5 | costRem = W - s 6 | itemsBought = costRem / L[i][0] 7 | itemsBought = min(L[i][1], itemsBought) 8 | count += itemsBought 9 | s += itemsBought * L[i][0] 10 | i += 1 11 | # print i, itemsBought, s 12 | return count 13 | 14 | if __name__ == '__main__': 15 | a, b, p = map(int, raw_input().split()) 16 | ca, cb, cp = map(int, raw_input().split()) 17 | W = input() 18 | 19 | L1 = [[a, ca], [b, cb], [p, cp]] 20 | L2 = [[a, ca], [p, cp], [b, cb]] 21 | L3 = [[b, cb], [a, ca], [p, cp]] 22 | L4 = [[b, cb], [p, cp], [a, ca]] 23 | L5 = [[p, cp], [a, ca], [b, cb]] 24 | L6 = [[p, cp], [b, cb], [a, ca]] 25 | print max(map(lambda x: getCost(W, x), [L1, L2, L3, L4, L5, L6])) 26 | -------------------------------------------------------------------------------- /code-py/fruitsExc.py: -------------------------------------------------------------------------------- 1 | 2 | def main(): 3 | for _ in xrange(input()): 4 | N, M, K = map(int, raw_input().split()) 5 | 6 | curDiff = abs(M - N) 7 | if K >= curDiff: 8 | print 0 9 | elif K < curDiff: 10 | print curDiff - K 11 | 12 | 13 | if __name__ == '__main__': 14 | main() 15 | -------------------------------------------------------------------------------- /code-py/gameofdrinks.py: -------------------------------------------------------------------------------- 1 | from math import sqrt,ceil 2 | 3 | def odd_divisors(a): 4 | fact_lis=[(i,a/i) for i in xrange(1,int(ceil(sqrt(a)))+1) if a%i ==0] 5 | my_fact=set() 6 | for i,j in fact_lis: 7 | if i%2!=0:my_fact.add(i) 8 | if j%2!=0:my_fact.add(j) 9 | 10 | print my_fact 11 | return len(my_fact) 12 | 13 | def main(): 14 | for _ in xrange(input()): 15 | wine_in_first = input() 16 | 17 | if wine_in_first==1: 18 | print 'Jaime Won' 19 | continue 20 | 21 | on_table = [wine_in_first] 22 | ways=odd_divisors(wine_in_first)-1 23 | 24 | if ways==0: 25 | print 'Jaime Won' 26 | 27 | else: 28 | print 'Tyrion Won' 29 | print ways+1 30 | 31 | 32 | 33 | if __name__ == '__main__': 34 | main() -------------------------------------------------------------------------------- /code-py/gasStation.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param gas : tuple of integers 3 | # @param cost : tuple of integers 4 | # @return an integer 5 | 6 | def canCompleteCircuit(self, gas, cost): 7 | n, first = len(gas), 0 8 | petrol = 0 9 | if sum(gas) < sum(cost): 10 | return -1 11 | 12 | for i in xrange(n): 13 | petrol += gas[i] - cost[i] 14 | if petrol < 0: 15 | first = i + 1 16 | petrol = 0 17 | 18 | return first 19 | 20 | if __name__ == '__main__': 21 | print Solution().canCompleteCircuit([3, 2, 6, 0], [2, 4, 3, 1]) 22 | -------------------------------------------------------------------------------- /code-py/geoCheat.py: -------------------------------------------------------------------------------- 1 | 2 | def dist(L): 3 | def euclid(a, b): 4 | return pow(a[0] - b[0], 2) + pow(a[1] - b[1], 2) 5 | 6 | if len(L) == 1: 7 | return 0 8 | N = len(L) 9 | maxDist = -1 10 | for i in xrange(N - 1): 11 | for j in xrange(i + 1, N): 12 | maxDist = max(maxDist, euclid(L[i], L[j])) 13 | return maxDist 14 | 15 | if __name__ == '__main__': 16 | N = input() 17 | L = [] 18 | for _ in xrange(N): 19 | L.append(map(int, raw_input().split())) 20 | print dist(L) 21 | -------------------------------------------------------------------------------- /code-py/goodString.py: -------------------------------------------------------------------------------- 1 | def vowel(c): 2 | return c in 'aeiou' 3 | 4 | 5 | def longGoodLength(S): 6 | n = len(S) 7 | dp = [0] * n 8 | for i, val in enumerate(S): 9 | if vowel(val): 10 | if i - 1 >= 0 and vowel(S[i - 1]): 11 | dp[i] = dp[i - 1] + 1 12 | else: 13 | dp[i] = 1 14 | else: 15 | dp[i] = 1 16 | return max(dp) 17 | 18 | if __name__ == '__main__': 19 | for _ in xrange(input()): 20 | N, K = map(int, raw_input().split()) 21 | A = map(int, raw_input().split()) 22 | print longGoodLength(S) 23 | -------------------------------------------------------------------------------- /code-py/goodSubSeq.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | S = raw_input() 4 | try: 5 | a = S.index('a') 6 | S = S[a:] 7 | S_ = S[::-1] 8 | c = len(S) - S_.index('c') 9 | S = S[:c] 10 | print S 11 | 12 | 13 | except ValueError: 14 | print 0 15 | -------------------------------------------------------------------------------- /code-py/goodlandElec.py: -------------------------------------------------------------------------------- 1 | def solve(N, K, A): 2 | last, P, ans = -1, [0] * N, 0 3 | 4 | for i in xrange(N): 5 | if A[i] == 1: 6 | last = i 7 | P[i] = last 8 | 9 | i = 0 10 | while i < N: 11 | take = P[min(i + K - 1, N - 1)] 12 | if take == -1 or take + K - 1 < i: 13 | return -1 14 | i = take + K 15 | ans += 1 16 | return ans 17 | 18 | if __name__ == '__main__': 19 | N, K = map(int, raw_input().split()) 20 | A = map(int, raw_input().split()) 21 | print solve(N, K, A) 22 | -------------------------------------------------------------------------------- /code-py/grayCode.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | # @param A : integer 4 | # @return a list of integers 5 | 6 | def grayCode(self, A): 7 | if A <= 0: 8 | return 9 | 10 | b, i = ['0', '1'], 2 11 | while i < (1 << A): 12 | b.extend(b[i - 1::-1]) 13 | 14 | for j in xrange(i): 15 | b[j] = '0' + b[j] 16 | 17 | for j in xrange(i, 2 * i): 18 | b[j] = '1' + b[j] 19 | 20 | i = i << 1 21 | 22 | return map(lambda x: int(x, 2), b) 23 | 24 | if __name__ == '__main__': 25 | print Solution().grayCode(input()) 26 | -------------------------------------------------------------------------------- /code-py/grguy.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t=int(sys.stdin.readline()) 4 | 5 | while t: 6 | L1=list(raw_input().strip()) 7 | L2=list(raw_input().strip()) 8 | assert len(L1)==len(L2) 9 | distance=len(L1) 10 | 11 | if L1[0]=='#'==L2[0] or L1[distance-1]=='#'==L2[distance-1]: 12 | print 'No' 13 | 14 | else: 15 | curr_pos,curr_lis,swaps=1,0,0 16 | L=[L1,L2] 17 | if L1[0]=='#':curr_lis=1 18 | 19 | while curr_pos!=distance: 20 | 21 | if L[curr_lis][curr_pos]=='#': 22 | 23 | if L[(curr_lis+1)%2][curr_pos]=='#': 24 | print 'No' 25 | break 26 | else: 27 | curr_lis=(curr_lis +1)%2 28 | curr_pos+=1 29 | swaps+=1 30 | 31 | else:curr_pos+=1 32 | 33 | if curr_pos==distance: 34 | print "Yes" 35 | print swaps 36 | t-=1 -------------------------------------------------------------------------------- /code-py/gridGreedy.py: -------------------------------------------------------------------------------- 1 | from heapq import heappop, heappush 2 | 3 | 4 | def solve(N, A): 5 | if N == 0: 6 | return 0 7 | A.sort() 8 | h = {} 9 | print A 10 | for i in A: 11 | print '\n For i: ', i 12 | if i not in h: 13 | h[i] = [] 14 | if i - 1 in h and len(h[i - 1]) > 0: 15 | heappush(h[i], heappop(h[i - 1]) + 1) 16 | else: 17 | heappush(h[i], 1) 18 | print h 19 | 20 | return min(h[x][0] for x in h if len(h[x])) 21 | 22 | if __name__ == '__main__': 23 | for _ in xrange(input()): 24 | A = map(int, raw_input().split()) 25 | N, A = A[0], A[1:] 26 | 27 | print solve(N, A) 28 | -------------------------------------------------------------------------------- /code-py/hibina.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | if __name__ == '__main__': 4 | N = input() 5 | h = defaultdict(set) 6 | for _ in xrange(N): 7 | A = map(str, raw_input().split()) 8 | for i in A[2:]: 9 | h[i].add(A[1]) 10 | 11 | for i in xrange(1, 6): 12 | key = str(i) 13 | l = h[key] 14 | if len(l) == 1: 15 | print 'NO' 16 | elif len(l) > 1: 17 | print 'YES' 18 | else: 19 | print 'UNDEFINED' 20 | -------------------------------------------------------------------------------- /code-py/html-tags.py: -------------------------------------------------------------------------------- 1 | import re 2 | from HTMLParser import HTMLParser 3 | 4 | class MyHTMLParser(HTMLParser): 5 | def handle_starttag(self, tag, attrs): 6 | print tag 7 | if attrs!=[]: 8 | for att,val in attrs: 9 | print '->',att,'>',val 10 | 11 | 12 | N=input() 13 | 14 | Parser=MyHTMLParser() 15 | while N: 16 | Parser.feed(raw_input()) 17 | N-=1 18 | 19 | """ 20 | 13 21 | #BED 22 | { 23 | color: #FfFdF8; background-color:#aef; 24 | font-size: 123px; 25 | #######898989#9898s9676#ajkjk 26 | #,#ichbineinhash #unddu#1100011#110010 27 | background: -webkit-linear-gradient(top, #f9f9f9, #fff); 28 | } 29 | #Cab 30 | { 31 | background-color: #ABC; 32 | border: 2px dashed #fff; 33 | } 34 | """ -------------------------------------------------------------------------------- /code-py/increasingSub.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | # @param A : list of integers 4 | # @return an integer 5 | 6 | def lcs(self, x, y): 7 | print 'LCS of ', x, ' and ', y 8 | m, n = len(x), len(y) 9 | L = [[0] * (n + 1) for i in xrange(m + 1)] 10 | for i in xrange(m + 1): 11 | for j in xrange(n + 1): 12 | if i == 0 or j == 0: 13 | L[i][j] = 0 14 | elif x[i - 1] == y[j - 1]: 15 | L[i][j] = L[i - 1][j - 1] + 1 16 | else: 17 | L[i][j] = max(L[i - 1][j], L[i][j - 1]) 18 | return L[m][n] 19 | 20 | def maxLCS(self, A): 21 | minJ, maxL = 0, 0 22 | for j in xrange(1, len(A)): 23 | ans = self.lcs(A[:j], A[j:][::-1]) 24 | print ans 25 | if ans > maxL: 26 | maxL = ans 27 | minJ = j 28 | return [minJ, maxL] 29 | 30 | if __name__ == '__main__': 31 | print Solution().maxLCS(raw_input()) 32 | -------------------------------------------------------------------------------- /code-py/insomnia.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def sleepBleatrix(N, inp): 4 | digits = set(list(str(N))) 5 | sleep = False 6 | 7 | for i in xrange(2, 100): 8 | for k in str(N * i): 9 | digits.add(str(k)) 10 | if len(digits) == 10: 11 | sleep = True 12 | N = N * i 13 | break 14 | 15 | if sleep: 16 | print 'CASE #%d: %d' % (inp + 1, N) 17 | else: 18 | print 'CASE #%d: %s' % (inp + 1, 'INSOMNIA') 19 | 20 | if __name__ == '__main__': 21 | for i in xrange(input()): 22 | N = input() 23 | sleepBleatrix(N, i) 24 | -------------------------------------------------------------------------------- /code-py/interBit.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : tuple of integers 3 | # @param B : integer 4 | # @return an integer. Searches element in rotated array 5 | 6 | def search(self, A, B): 7 | return self.searchRec(A, 0, len(A) - 1, B) 8 | 9 | def searchRec(self, A, l, h, B): 10 | if l > h: 11 | return -1 12 | m = (l + h) / 2 13 | if A[m] == B: 14 | return m 15 | 16 | if A[l] <= A[m]: 17 | if B >= A[l] and B <= A[m]: 18 | return self.searchRec(A, l, m - 1, B) 19 | return self.searchRec(A, m + 1, h, B) 20 | 21 | if B >= A[m] and B <= A[h]: 22 | return self.searchRec(A, m + 1, h, B) 23 | 24 | return self.searchRec(A, l, m - 1, B) 25 | 26 | 27 | def main(): 28 | A = map(int, raw_input().split()) 29 | B = input() 30 | S = Solution() 31 | print S.search(A, B) 32 | 33 | 34 | if __name__ == '__main__': 35 | main() 36 | -------------------------------------------------------------------------------- /code-py/jpStrings.py: -------------------------------------------------------------------------------- 1 | 2 | mod = 1000000007 3 | 4 | 5 | def f(N, L): 6 | left, right = 1, 1 7 | if N < L: 8 | left = pow(N - 1, N, mod) 9 | right = pow(N, L - N, mod) 10 | return (left * right) % mod 11 | else: 12 | left = pow(N - 1, L, mod) 13 | return left 14 | 15 | 16 | if __name__ == '__main__': 17 | for _ in xrange(input()): 18 | N, L = map(int, raw_input().split()) 19 | print f(N, L) 20 | -------------------------------------------------------------------------------- /code-py/just_mult.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t=int(sys.stdin.readline()) 4 | m,lis=0,[] 5 | 6 | while t: 7 | m,lis=raw_input().strip().split() 8 | 9 | n,m,temp=len(lis),int(m),1 10 | 11 | lis=lis.replace('**',' ') 12 | lis=lis.split('*') 13 | 14 | for i in lis: 15 | no,temp2=map(int,i.split()) 16 | temp*=pow(no,temp2,m) 17 | 18 | print temp%m 19 | t-=1 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /code-py/kitchenTT.py: -------------------------------------------------------------------------------- 1 | 2 | def solve(K, C): 3 | _p = pow(K, 3) 4 | rem = _p - C 5 | for i in xrange(101): 6 | r = pow(i, 3) - C 7 | if r % _p == 0: 8 | return 'YES' 9 | 10 | return 'NO' 11 | 12 | if __name__ == '__main__': 13 | for _ in xrange(input()): 14 | K, C = map(int, raw_input().split()) 15 | print solve(K, C) 16 | -------------------------------------------------------------------------------- /code-py/kthFractionNthStep.py: -------------------------------------------------------------------------------- 1 | 2 | def main(): 3 | N, K = map(int, raw_input().split()) 4 | 5 | 6 | if __name__ == "__main__": 7 | main() 8 | -------------------------------------------------------------------------------- /code-py/kthSmall.py: -------------------------------------------------------------------------------- 1 | 2 | N, Q = map(int, raw_input().split()) 3 | N = N + 1 4 | S = '0' + raw_input() 5 | 6 | P = [[0] * 26 for i in xrange(N)] 7 | for i in xrange(1, N): 8 | d = ord(S[i]) - ord('a') 9 | for j in xrange(26): 10 | if j == d: 11 | P[i][j] = P[i - 1][j] + 1 12 | else: 13 | P[i][j] = P[i - 1][j] 14 | 15 | for i in P[1:]: 16 | print i 17 | 18 | for _ in xrange(Q): 19 | L, R, K = map(int, raw_input().split()) 20 | Kthsmall, j = 0, 0 21 | 22 | while j < 26: 23 | Kthsmall += P[R][j] - P[L - 1][j] 24 | if Kthsmall >= K: 25 | break 26 | j += 1 27 | ans = chr(97 + j) 28 | if j == 26: 29 | print 'Out of range' 30 | else: 31 | print ans 32 | -------------------------------------------------------------------------------- /code-py/kthmax.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def allSubArrays(A, N): 4 | """Store all subarrays of A""" 5 | sub = [] 6 | for i in xrange(N): 7 | for j in xrange(i, N): 8 | sub.append(A[i:j + 1]) 9 | sub[-1] += [0] * (N - len(sub[-1])) 10 | return sub 11 | 12 | 13 | if __name__ == '__main__': 14 | for _ in xrange(input()): 15 | N, M = map(int, raw_input().split()) 16 | A = map(int, raw_input().split()) 17 | sub = sorted(allSubArrays(A, N))[::-1] 18 | 19 | for __ in xrange(M): 20 | P = input() 21 | print max(sub[P - 1]) 22 | -------------------------------------------------------------------------------- /code-py/lampPost.py: -------------------------------------------------------------------------------- 1 | 2 | # How to efficiently merge intervals given k queries 3 | 4 | 5 | def mergeInterval(l): 6 | l.sort() 7 | res = [l[0]] 8 | for i in xrange(1, len(l)): 9 | prev, cur = res[-1], l[i] 10 | if prev[1] >= cur[0]: 11 | prev[1] = max(prev[1], cur[1]) 12 | else: 13 | res.append(cur) 14 | return sum([i[1] - i[0] + 1 for i in res]) 15 | 16 | if __name__ == '__main__': 17 | N, M, k = map(int, raw_input().split()) 18 | 19 | total = N * M 20 | H = {} 21 | 22 | for _ in xrange(k): 23 | r, c1, c2 = map(int, raw_input().split()) 24 | if r not in H: 25 | H[r] = [[c1, c2]] 26 | else: 27 | H[r].append([c1, c2]) 28 | for i in H: 29 | total -= mergeInterval(H[i]) 30 | print total 31 | -------------------------------------------------------------------------------- /code-py/larg.py: -------------------------------------------------------------------------------- 1 | 2 | t=int(raw_input()) #compute the largest of the sums of numbers that appear on the paths starting from the top towards the base 3 | 4 | for _ in xrange(t): 5 | n=int(raw_input()) 6 | 7 | lis=[[0 for _ in xrange(n)] for _ in xrange(n)] 8 | 9 | for i in xrange(n): 10 | lis[i]=map(int,raw_input().split()) 11 | 12 | for i in xrange(n-1,-1,-1): 13 | for j in xrange(i): 14 | if lis[i][j]>lis[i][j+1]: 15 | lis[i-1][j]+=lis[i][j] 16 | else: 17 | lis[i-1][j]+=lis[i][j+1] 18 | 19 | print lis[0][0] 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /code-py/largestBou.py: -------------------------------------------------------------------------------- 1 | if __name__ == '__main__': 2 | for _ in xrange(input()): 3 | r1, g1, b1 = map(int, raw_input().split()) 4 | r2, g2, b2 = map(int, raw_input().split()) 5 | r3, g3, b3 = map(int, raw_input().split()) 6 | sg1 = r1 + g1 + b1 7 | sg2 = r2 + g2 + b2 8 | sg3 = r3 + g3 + b3 9 | 10 | if sg1 % 2 == 0: 11 | sg1 -= 1 12 | if sg2 % 2 == 0: 13 | sg2 -= 1 14 | if sg3 % 2 == 0: 15 | sg3 -= 1 16 | 17 | ss1 = r1 + r2 + r3 18 | ss2 = g1 + g2 + g3 19 | ss3 = b1 + b2 + b3 20 | if ss1 % 2 == 0: 21 | ss1 -= 1 22 | if ss2 % 2 == 0: 23 | ss2 -= 1 24 | if ss3 % 2 == 0: 25 | ss3 -= 1 26 | # print 'max: ', [sg1, sg2, sg3, ss1, ss2, ss3] 27 | maxm = max(0, max([sg1, sg2, sg3, ss1, ss2, ss3])) 28 | print maxm 29 | -------------------------------------------------------------------------------- /code-py/lastWord.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | 4 | def printLastWord(S, inp): 5 | T = deque() 6 | for i in S: 7 | if not T: 8 | T.append(i) 9 | else: 10 | if ord(i) >= ord(T[0]): 11 | T.appendleft(i) 12 | else: 13 | T.append(i) 14 | print 'Case #%d:' % (inp + 1), ''.join(T) 15 | 16 | 17 | if __name__ == '__main__': 18 | for i in xrange(input()): 19 | S = raw_input() 20 | printLastWord(S, i) 21 | -------------------------------------------------------------------------------- /code-py/lcs.py: -------------------------------------------------------------------------------- 1 | "Find longest subsequence in two strings" 2 | 3 | def longest_subsequence(a,b): 4 | m, n = len(a) , len(b) 5 | 6 | """Recursive 7 | if m == 0 or n == 0 : 8 | return 0 9 | 10 | elif a[m-1] == b[n-1]: 11 | return 1 + longest_subsequence(a[:m-1], b[:n-1]) 12 | 13 | else: 14 | return max(longest_subsequence(a[:m], b[:n-1]), longest_subsequence(a[:m-1], b[:n])) 15 | """ 16 | 17 | L = [[None]*(n+1) for m in xrange(m+1)] 18 | 19 | for i in xrange(m+1): 20 | for j in xrange(n+1): 21 | if i == 0 or j == 0: 22 | L[i][j] = 0 23 | elif a[i-1] == b[j-1]: 24 | L[i][j] = L[i-1][j-1]+1 25 | else: 26 | L[i][j] = max(L[i][j-1], L[i-1][j]) 27 | 28 | return L[m][n] 29 | 30 | def main(): 31 | a = raw_input() 32 | b = raw_input() 33 | print longest_subsequence(a,b) 34 | 35 | 36 | if __name__ == '__main__': 37 | main() 38 | 39 | -------------------------------------------------------------------------------- /code-py/lead.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | a=int(raw_input()) #determine which player wins and by how much 4 | lis=[] 5 | a1,a2=0,0 6 | while a: 7 | b,c= map(int,sys.stdin.readline().split()) 8 | a1+=b 9 | a2+=c 10 | lis.append(a1-a2) 11 | a-=1 12 | 13 | if max(lis)>abs(min(lis)): 14 | print '1 ',max(lis) 15 | else: 16 | print '2',abs(min(lis)) 17 | -------------------------------------------------------------------------------- /code-py/learniter.py: -------------------------------------------------------------------------------- 1 | from itertools import * 2 | name=['A','B'] 3 | surname=[1,2] 4 | 5 | for i in chain(name,surname): 6 | print i 7 | 8 | for i in izip(name,surname): 9 | print ''.join(list(str(x) for x in i)) 10 | print i 11 | 12 | lis=[range(100)] 13 | for i in islice(count(),10): 14 | print i, 15 | -------------------------------------------------------------------------------- /code-py/lfive.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | n,q=[int(i) for i in raw_input().split()] 4 | lis=map(int,raw_input().split()) 5 | 6 | while q: 7 | L,R=[int(i)-1 for i in raw_input().split()] 8 | t=lis[L:R+1] 9 | count=0 10 | 11 | for i in xrange(1,len(t)-4+1): 12 | for j in xrange(i+1,len(t)-3+1): 13 | for k in xrange(j+1,len(t)-2+1): 14 | if t[L]>t[i]t[k] odd: 8 | print 'READY FOR BATTLE' 9 | else: 10 | print 'NOT READY' 11 | -------------------------------------------------------------------------------- /code-py/makeArrayEq.py: -------------------------------------------------------------------------------- 1 | 2 | from collections import Counter 3 | 4 | if __name__ == '__main__': 5 | N = input() 6 | A = map(int, raw_input().split()) 7 | D = Counter(A) 8 | print N - D.most_common(1)[0][1] 9 | -------------------------------------------------------------------------------- /code-py/mandraDp.py: -------------------------------------------------------------------------------- 1 | 2 | def brute(H): 3 | S, P = 1, 0 4 | # how many do we eat : N possibilities 5 | maxP = 0 6 | for k in xrange(len(H)): 7 | # eat before and battle after 8 | S = (k + 1) 9 | P = Pre[k] * S 10 | maxP = max(maxP, P) 11 | return maxP 12 | 13 | 14 | if __name__ == '__main__': 15 | for _ in xrange(input()): 16 | N = input() 17 | H = sorted(map(int, raw_input().split())) 18 | Pre = [H[-1]] * N 19 | for i in xrange(N - 2, -1, -1): 20 | Pre[i] = Pre[i + 1] + H[i] 21 | print Pre 22 | print brute(H) 23 | -------------------------------------------------------------------------------- /code-py/maxCircle.py: -------------------------------------------------------------------------------- 1 | 2 | def dfs(i, sumT, V, G): 3 | if V[i] == 1: 4 | return sumT 5 | else: 6 | V[i] = 1 7 | sumT += 1 8 | if V[G[i]] == 1: 9 | return sumT 10 | return dfs(G[i], sumT, V, G) 11 | 12 | 13 | def maxCircle(N, B, inp): 14 | G = {} 15 | hasBFF = {} 16 | 17 | for i in xrange(N): 18 | G[i] = B[i] - 1 19 | try: 20 | hasBFF[B[i] - 1].append(i) 21 | except: 22 | hasBFF[B[i] - 1] = [i] 23 | 24 | print G 25 | print hasBFF 26 | 27 | maxM = 0 28 | for i in xrange(N): 29 | V = [0 for k in xrange(N)] 30 | maxCycle = dfs(i, 0, V, G) 31 | maxM = max(maxM, maxCycle) 32 | print 'Case #%d:' % (inp + 1), maxM 33 | 34 | 35 | if __name__ == '__main__': 36 | for _ in xrange(input()): 37 | N = input() 38 | B = map(int, raw_input().split()) 39 | maxCircle(N, B, _) 40 | -------------------------------------------------------------------------------- /code-py/maxKSum.py: -------------------------------------------------------------------------------- 1 | 2 | import heapq 3 | 4 | 5 | def solver(N, K, A): 6 | ans, heap = [], [] 7 | prefix = [A[0]] 8 | for x in A[1:]: 9 | prefix.append(prefix[-1] + x) 10 | 11 | indexMap = set() 12 | heapq.heappush(heap, (-prefix[-1], 0, N - 1)) 13 | indexMap.add((0, N - 1)) 14 | 15 | while K > 0 and len(heap) != 0: 16 | val, i, j = heapq.heappop(heap) 17 | val = -val 18 | ans.append(val) 19 | if i != j: 20 | if (i + 1, j) not in indexMap: 21 | heapq.heappush(heap, (-(val - A[i]), i + 1, j)) 22 | indexMap.add((i + 1, j)) 23 | 24 | if (i, j - 1) not in indexMap: 25 | heapq.heappush(heap, (-(val - A[j]), i, j - 1)) 26 | indexMap.add((i, j - 1)) 27 | 28 | K -= 1 29 | return ans 30 | 31 | 32 | if __name__ == '__main__': 33 | N, K = map(int, raw_input().split()) 34 | A = map(int, raw_input().split()) 35 | 36 | print ' '.join([str(i) for i in solver(N, K, A)]) 37 | -------------------------------------------------------------------------------- /code-py/maxiSum.py: -------------------------------------------------------------------------------- 1 | # my solve 2 | def solve(): 3 | _, k = map(int, raw_input().split()) 4 | A = map(int, raw_input().split()) 5 | B = map(int, raw_input().split()) 6 | return sum(a * b for a, b in zip(A, B)) + k * max(map(abs, B)) 7 | 8 | if __name__ == '__main__': 9 | for _ in xrange(input()): 10 | print solve() 11 | -------------------------------------------------------------------------------- /code-py/maximalSub.py: -------------------------------------------------------------------------------- 1 | def solve(A, K): 2 | H = [0 for i in xrange(K)] 3 | 4 | for i in A: 5 | H[i % K] += 1 6 | 7 | c = 1 if H[0] > 0 else 0 8 | i, j = 1, K - 1 9 | while i <= j: 10 | if i < j: 11 | c += max(H[i], H[j]) 12 | elif i == j: 13 | c += 1 if H[i] > 0 else 0 14 | i += 1 15 | j -= 1 16 | return c 17 | 18 | 19 | if __name__ == '__main__': 20 | N, K = map(int, raw_input().split()) 21 | A = map(int, raw_input().split()) 22 | print solve(A, K) 23 | -------------------------------------------------------------------------------- /code-py/maximize-it.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | K,M=map(int,raw_input().split()) 4 | lists=[] 5 | 6 | while K: 7 | lis=map(int,raw_input().split()) 8 | lis=[ i*i for i in lis[1:] ] 9 | 10 | lists.append(lis) 11 | K-=1 12 | 13 | ans=0 14 | 15 | for i in list(itertools.product(*lists)): 16 | temp=sum(i)%M 17 | if temp>ans: 18 | ans=temp 19 | print (ans+M)%M -------------------------------------------------------------------------------- /code-py/maxxor.py: -------------------------------------------------------------------------------- 1 | def getMSB(number): #Find max xor with given element 2 | no_of_bits=0 3 | while number: 4 | number=number>>1 5 | no_of_bits+=1 6 | 7 | return no_of_bits 8 | 9 | def maxXor(tlis,x): 10 | maximum=max(tlis) 11 | 12 | if getMSB(x)Kevin:print 'Stuart',Stuart 17 | elif Kevin>Stuart:print 'Kevin',Kevin 18 | else:print 'Draw' 19 | 20 | -------------------------------------------------------------------------------- /code-py/monkInteger.py: -------------------------------------------------------------------------------- 1 | 2 | def getWindow(A, w): 3 | N = len(A) 4 | max_l = [0] * N 5 | max_r = [0] * N 6 | max_l[0], max_r[-1] = A[0], A[-1] 7 | for i in xrange(1, N): 8 | max_l[i] = A[i] if i % w == 0 else max(max_l[i - 1], A[i]) 9 | j = N - i - 1 10 | max_r[j] = A[j] if i % w == 0 else max(max_r[j + 1], A[j]) 11 | 12 | B = [0] * (N - w + 1) 13 | j = 0 14 | for i in xrange(N - w + 1): 15 | B[j] = max(max_r[i], max_l[i + w - 1]) 16 | j += 1 17 | return B 18 | 19 | 20 | if __name__ == '__main__': 21 | N, X = map(int, raw_input().split()) 22 | A = map(int, raw_input().split()) 23 | 24 | h = {} 25 | -------------------------------------------------------------------------------- /code-py/monkMod.py: -------------------------------------------------------------------------------- 1 | from math import ceil 2 | 3 | if __name__ == '__main__': 4 | N = input() 5 | A = map(str, raw_input().split()) 6 | max_i = int(ceil(len(str(max(A))) * 1.0 / 5)) 7 | A = map(lambda x: x.zfill(max_i * 5), A) 8 | A = [[i, 0] for i in A] 9 | 10 | B = A[:] 11 | for i in xrange(1, max_i + 1): 12 | l, r = 1 + 5 * (i - 1), 5 * i 13 | for _j in xrange(len(B)): 14 | j = B[_j][0] 15 | val = j[-r:-l + 1] if i != 1 else j[-r:] 16 | val = int(val) 17 | B[_j][1] = (str(val)) 18 | B.sort(key=lambda x: x[1]) 19 | for i in B: 20 | print i[0].lstrip('0'), 21 | print 22 | -------------------------------------------------------------------------------- /code-py/monkMountain.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect 2 | 3 | if __name__ == '__main__': 4 | N, Q = map(int, raw_input().split()) 5 | L = [] 6 | P = [0] * N 7 | for _ in xrange(N): 8 | L.append(map(int, raw_input().split())) 9 | P[0] = L[0][1] - L[0][0] + 1 10 | for i in xrange(1, N): 11 | P[i] = P[i - 1] + L[i][1] - L[i][0] + 1 12 | 13 | for _ in xrange(Q): 14 | X = input() 15 | ind = bisect(P, X - 1) 16 | if ind == 0: 17 | print X + L[ind][0] - 1 18 | elif ind == N: 19 | print L[-1][1] 20 | else: 21 | X = X - P[ind - 1] 22 | print X + L[ind][0] - 1 23 | -------------------------------------------------------------------------------- /code-py/most-distant.py: -------------------------------------------------------------------------------- 1 | 2 | def distance(p1, p2): 3 | return pow((p2[0] - p1[0])**2.0 + (p2[1] - p1[1])**2.0, 0.5) 4 | 5 | 6 | def main(): 7 | lis = [] 8 | for i in xrange(input()): 9 | a, b = map(int, raw_input().split()) 10 | lis.append((a, b)) 11 | 12 | max_l = min(lis, key=lambda x: x[0]) 13 | max_r = max(lis, key=lambda x: x[0]) 14 | max_t = max(lis, key=lambda x: x[1]) 15 | max_b = min(lis, key=lambda x: x[1]) 16 | 17 | lis = [] 18 | lis.append(distance(max_l, max_r)) 19 | lis.append(distance(max_l, max_t)) 20 | lis.append(distance(max_l, max_b)) 21 | lis.append(distance(max_t, max_b)) 22 | lis.append(distance(max_b, max_r)) 23 | lis.append(distance(max_t, max_r)) 24 | 25 | print "%6f" % max(lis) 26 | 27 | if __name__ == '__main__': 28 | main() 29 | -------------------------------------------------------------------------------- /code-py/movieWeek.py: -------------------------------------------------------------------------------- 1 | 2 | def findOptimalMovie(L): 3 | M = [(L[i][0] * L[i][1], L[i][1], i) for i in xrange(len(L))] 4 | A = sorted(M, key=lambda x: (-x[0], -x[1], x[2])) 5 | # print A 6 | print A[0][2] + 1 7 | 8 | if __name__ == '__main__': 9 | for _ in xrange(input()): 10 | N = input() 11 | L = zip(map(int, raw_input().split()), map(int, raw_input().split())) 12 | findOptimalMovie(L) 13 | -------------------------------------------------------------------------------- /code-py/nonOverlappingIntervals.py: -------------------------------------------------------------------------------- 1 | def eraseOverlapIntervals(intervals): 2 | if len(intervals) == 0: 3 | return 0 4 | intervals = sorted(intervals, key=lambda x: x[1]) 5 | end, cnt = intervals[0][1], 0 6 | for s, e in intervals[1:]: 7 | if s >= end: 8 | end = e 9 | else: 10 | # overlap 11 | cnt += 1 12 | return cnt 13 | 14 | 15 | if __name__ == "__main__": 16 | # print (merge([[8, 10], [1, 3], [15, 18], [2, 6]])) 17 | # print (merge([[1, 4], [4, 5]])) 18 | # print (eraseOverlapIntervals([[1, 2], [2, 3], [3, 4], [1, 3]])) 19 | # print (eraseOverlapIntervals([[1, 2], [1, 2], [1, 2]])) 20 | print (eraseOverlapIntervals([[1, 2], [2, 3]])) 21 | -------------------------------------------------------------------------------- /code-py/orderChairPerson.py: -------------------------------------------------------------------------------- 1 | 2 | def main(): 3 | A = input().split() 4 | N = int(A[0]) 5 | attendees = list(map(lambda x: (x[0]).upper(), A[1:])) 6 | attendeeOrder = {k + 1: v for k, v in enumerate(attendees)} 7 | attendeeOrder[0] = 'X' 8 | 9 | maxWidth = maxDepth = 2 * N + 1 10 | 11 | for i in range(1, maxDepth + 1): 12 | for j in range(1, maxWidth + 1): 13 | print (nationThatBelongsHere(i, j, N, attendeeOrder), end=' ') 14 | print () 15 | 16 | 17 | def nationThatBelongsHere(i, j, N, attendeeOrder): 18 | max_X_dist = absHorizontalDistanceFromX(j, N) 19 | max_Y_dist = absVerticalDistanceFromX(i, N) 20 | return attendeeOrder[max(max_X_dist, max_Y_dist)] 21 | 22 | 23 | def absVerticalDistanceFromX(i, N): 24 | y_coord_Center = N + 1 25 | return abs(y_coord_Center - i) 26 | 27 | 28 | def absHorizontalDistanceFromX(j, N): 29 | x_coord_Center = N + 1 30 | return abs(x_coord_Center - j) 31 | 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /code-py/paintbox.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t=int(sys.stdin.readline()) 4 | 5 | while t: 6 | list=[] 7 | n,w=map(int,raw_input().split()) 8 | lis=map(int,raw_input().split()) 9 | q=int(raw_input()) 10 | 11 | while q: 12 | pos,col=map(int,raw_input().split()) 13 | lis[pos-1],count,i=col,0,0 14 | 15 | for i in xrange(0,len(lis)-1): 16 | if lis[i]==lis[i+1]: 17 | count+=1 18 | 19 | print count 20 | q-=1 21 | t-=1 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /code-py/palSubstr.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isopropylcyanide/Competitive-Programming/cf7dd54728c8e816c78904070b199dd709232e28/code-py/palSubstr.py -------------------------------------------------------------------------------- /code-py/pal_anagram.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | """ 4 | Determine if string is palindromic anagram 5 | """ 6 | 7 | s = Counter(raw_input()) 8 | 9 | palindromic_perm = True 10 | length = sum(s.viewvalues()) 11 | 12 | if length % 2 == 0: 13 | # count of all elements should be even 14 | for i in s.itervalues(): 15 | if i & 1: 16 | palindromic_perm = False 17 | break 18 | 19 | else: 20 | # count of only one element is odd , rest all even 21 | found_one_odd = False 22 | 23 | for i in s.itervalues(): 24 | if i & 1 and found_one_odd is False: 25 | found_one_odd = True 26 | elif i & 1 and found_one_odd is True: 27 | palindromic_perm = False 28 | break 29 | 30 | print 'YES' if palindromic_perm else 'NO' 31 | 32 | -------------------------------------------------------------------------------- /code-py/palinSubstr.py: -------------------------------------------------------------------------------- 1 | def solve(a, b): 2 | if len(set(a).intersection(set(b))) > 0: 3 | print 'Yes' 4 | else: 5 | print 'No' 6 | 7 | if __name__ == '__main__': 8 | for _ in xrange(input()): 9 | solve(raw_input(), raw_input()) 10 | -------------------------------------------------------------------------------- /code-py/palsub.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | def is_palin(s): 4 | return s==s[::-1] 5 | 6 | def main(): 7 | for _ in xrange(input()): 8 | n=input() 9 | string=raw_input() 10 | 11 | P=[[False]*n]*n 12 | C=[0]*n 13 | 14 | for i in xrange(n-1): 15 | for j in xrange(i+1,n): 16 | if is_palin(string[i:j+1]): 17 | P[i][j]=True 18 | 19 | for i in xrange(n): 20 | for j in xrange(n): 21 | print string[i:j+1],P[i][j], 22 | print 23 | 24 | 25 | for i in xrange(n): 26 | if P[0][i]==True: 27 | C[i]=0 28 | 29 | else: 30 | C[i]=10 31 | for j in xrange(i): 32 | if P[j+1][i] == True and C[j]+1> 1 14 | print '}' 15 | 16 | 17 | def permuteUtil(i, s, A): 18 | if i == len(A): 19 | s.add(tuple(A)) 20 | return 21 | for j in xrange(i, len(A)): 22 | b = A[:] 23 | (b[i], b[j]) = (b[j], b[i]) 24 | permuteUtil(i + 1, s, b) 25 | 26 | 27 | def permute(A): 28 | s = set() 29 | permuteUtil(0, s, A) 30 | return s 31 | 32 | if __name__ == '__main__': 33 | print permute(map(int, raw_input().split())) 34 | -------------------------------------------------------------------------------- /code-py/powerplants.py: -------------------------------------------------------------------------------- 1 | def getDist(V): 2 | n = len(V) 3 | dist = [0] * n 4 | 5 | # ls rs denotes left and right end of nearest ss 6 | ls, rs = 0, 0 7 | for j in xrange(n): 8 | if V[j] == 1: 9 | ls = rs = j 10 | break 11 | 12 | for i in xrange(n): 13 | if V[i] == 1: 14 | dist[i] = 0 15 | ls = i 16 | rs = i 17 | for j in xrange(i + 1, n): 18 | if V[j] == 1: 19 | rs = j 20 | break 21 | else: 22 | minm = min(abs(i - ls), abs(rs - i)) 23 | dist[i] = minm 24 | 25 | print max(dist) 26 | 27 | n, m = map(int, raw_input().strip().split(' ')) 28 | c = map(int, raw_input().strip().split(' ')) 29 | V = [0] * n 30 | for i in c: 31 | V[i] = 1 32 | 33 | getDist(V) 34 | -------------------------------------------------------------------------------- /code-py/pratFrie.py: -------------------------------------------------------------------------------- 1 | def solve(N, K, l): 2 | # Calculate prefix sum 3 | i, j = 0, 0 4 | cur = l[0] 5 | 6 | found = False 7 | while j < N: 8 | if cur > K: 9 | cur -= l[i] 10 | i += 1 11 | elif cur == K: 12 | found = True 13 | break 14 | else: 15 | j += 1 16 | cur += l[j] 17 | if i > j: 18 | j += 1 19 | return "YES" if found else "NO" 20 | 21 | 22 | if __name__ == "__main__": 23 | for _ in xrange(input()): 24 | N, K = map(int, raw_input().split()) 25 | l = [] 26 | for i in xrange(N): 27 | l.append(input()) 28 | 29 | print solve(N, K, l) 30 | -------------------------------------------------------------------------------- /code-py/prefixNum.py: -------------------------------------------------------------------------------- 1 | """ 2 | Build a number with n digits. Start with a number without any digits. There will be n moves. In each move players append one digit to a number so a new digit will be the last digit after the move. The only rule is: after every appended digit, the number has to be divisible by this digit. It implies that they can never add a digit 0 3 | """ 4 | 5 | mod = 2 ** 32 6 | 7 | from itertools import product 8 | 9 | if __name__ == '__main__': 10 | for N in xrange(1, 100): 11 | 12 | count = 0 13 | A = range(1, 10) 14 | for i in product(A, repeat=N): 15 | a = ''.join([str(k) for k in i]) 16 | last = int(a[-1]) 17 | if int(a) % last == 0: 18 | count = (count + 1) % mod 19 | 20 | print 'i: ', N, ' - ', count 21 | -------------------------------------------------------------------------------- /code-py/primitiveRoot.py: -------------------------------------------------------------------------------- 1 | 2 | def isPrimitive(r, p): 3 | # Check if r is a primitive root of p 4 | L = [] 5 | for i in xrange(p - 1): 6 | L.append(pow(r, i, p)) 7 | if len(L) == len(set(L)): 8 | return True 9 | return False 10 | 11 | if __name__ == '__main__': 12 | N = input() 13 | minm, tot = None, 0 14 | for i in xrange(1, N): 15 | if isPrimitive(i, N): 16 | if minm is None: 17 | minm = i 18 | tot += 1 19 | else: 20 | tot += 1 21 | print minm, tot 22 | -------------------------------------------------------------------------------- /code-py/progressPie.py: -------------------------------------------------------------------------------- 1 | from math import degrees, acos, sqrt 2 | 3 | 4 | def dist(X, Y): 5 | """Dist from center to X, Y <= 50""" 6 | return True if pow(X - 50, 2) + pow(Y - 50, 2) <= 2500 else False 7 | 8 | 9 | def angle(x, y): 10 | num = y - 50 11 | if num == 0 and x - 50 == 0: 12 | return 360 13 | den = sqrt(pow(x - 50, 2) + pow(y - 50, 2)) 14 | a = degrees(acos(num / den)) 15 | if x < 50: 16 | return 360 - a 17 | else: 18 | return a 19 | 20 | if __name__ == '__main__': 21 | for _ in xrange(input()): 22 | P, X, Y = map(int, raw_input().split()) 23 | ans = 'white' 24 | 25 | angle_cov = (P * 360.0) / 100 26 | angle_point = angle(X, Y) 27 | if angle_point <= angle_cov and dist(X, Y): 28 | ans = 'black' 29 | 30 | print 'Case #%d: %s' % (_ + 1, ans) 31 | -------------------------------------------------------------------------------- /code-py/qset.py: -------------------------------------------------------------------------------- 1 | #string queries. 1. replace 2. check for substring divisibilty by 3 2 | import itertools 3 | 4 | n,m=map(int,raw_input().split()) 5 | 6 | lis=map(int,raw_input()) 7 | 8 | while m: 9 | query_no,init,final=map(int,raw_input().split()) 10 | init,final=init-1,final-1 11 | count=0 12 | if query_no==1: 13 | lis[init]=final+1 14 | 15 | elif query_no==2: 16 | count=0 17 | r0,r1,r2=0,0,0 18 | for i in xrange(init,final+1): 19 | r=int(lis[i])%3 20 | if r==0: 21 | r0+=1 22 | elif r==1: 23 | r0,r1,r2=r2,r0,r1 24 | r1+=1 25 | elif r==2: 26 | r0,r1,r2=r1,r2,r0 27 | r2+=1 28 | count+=r0 29 | print count 30 | 31 | m-=1 32 | 33 | 34 | -------------------------------------------------------------------------------- /code-py/quantum_land.py: -------------------------------------------------------------------------------- 1 | 2 | def main(): 3 | for _ in xrange(input()): 4 | n=input() 5 | b=map(int,raw_input().strip().split()) 6 | 7 | guard=0 8 | for i in xrange(n-1): 9 | if b[i+1]!=1 and b[i]!=1: 10 | guard+=1 11 | b[i+1]=1 12 | 13 | print guard 14 | 15 | 16 | if __name__ == '__main__': 17 | main() -------------------------------------------------------------------------------- /code-py/rainWater.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : tuple of integers 3 | # @return an integer 4 | 5 | def trap(self, A): 6 | maxSeenSoFar, maxSeenLeft, totalTrap = 0, 0, 0 7 | maxSeenRight = [0 for i in xrange(len(A))] 8 | 9 | for i in xrange(len(A) - 1, -1, -1): 10 | if A[i] > maxSeenSoFar: 11 | maxSeenSoFar = A[i] 12 | maxSeenRight[i] = maxSeenSoFar 13 | else: 14 | maxSeenRight[i] = maxSeenSoFar 15 | 16 | for i in xrange(len(A)): 17 | totalTrap += max(min(maxSeenLeft, maxSeenRight[i]) - A[i], 0) 18 | if A[i] > maxSeenLeft: 19 | maxSeenLeft = A[i] 20 | 21 | return totalTrap 22 | 23 | if __name__ == '__main__': 24 | print Solution().trap([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]) 25 | 26 | 27 | # 28 | 29 | 30 | # 31 | -------------------------------------------------------------------------------- /code-py/rankAndFile.py: -------------------------------------------------------------------------------- 1 | import itertools as it 2 | from collections import Counter 3 | 4 | 5 | def missingRow(N, L, inp): 6 | d = Counter(list(it.chain.from_iterable(L))) 7 | S = sorted([i for i in d if d[i] % 2 == 1]) 8 | 9 | print 'Case #%d:' % (inp + 1), ' '.join([str(k) for k in S]) 10 | 11 | 12 | if __name__ == '__main__': 13 | for _ in xrange(input()): 14 | N = input() 15 | L = [] 16 | for i in xrange(2 * N - 1): 17 | L.append(map(int, raw_input().split())) 18 | missingRow(N, L, _) 19 | -------------------------------------------------------------------------------- /code-py/ranklist.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t=int(sys.stdin.readline()) 4 | 5 | while t: 6 | n,gsum=map(int,raw_input().split()) 7 | op,tsum=0,n*(n+1)/2 8 | 9 | if gsum in [1,tsum]: 10 | print 0 11 | elif gsum==n: 12 | print n-1 13 | else: 14 | print abs(tsum-gsum)%n 15 | t-=1 16 | 17 | 18 | -------------------------------------------------------------------------------- /code-py/redundantBrace.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | # @param A : string 4 | # @return an integer 5 | 6 | def matches(self, c, s): 7 | if c == ')': 8 | return True if s[-1] == '(' else False 9 | elif c == '}': 10 | return True if s[-1] == '{' else False 11 | elif c == ']': 12 | return True if s[-1] == '[' else False 13 | 14 | def braces(self, A): 15 | braces = 0 16 | for char in A: 17 | if char == '(': 18 | braces += 1 19 | elif char in "*/+-": 20 | braces -= 1 21 | if braces < 0: 22 | braces = 0 23 | if braces == 0: 24 | return 0 25 | else: 26 | return 1 27 | 28 | 29 | if __name__ == '__main__': 30 | a = '((a + b))' 31 | b = '(a + (a + b))' 32 | print Solution().braces(a) 33 | print Solution().braces(b) 34 | -------------------------------------------------------------------------------- /code-py/regex_group.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | time = raw_input() 4 | times = re.search(r"(?P..):(?P..):(?P..)(?P..)", time) 5 | hour = times.group('hh') 6 | 7 | if times.group('ampm') == 'PM': 8 | if hour == '12': 9 | hr = '12' 10 | else: 11 | hr = str(int(hour) + 12) 12 | else: 13 | if hour == '12': 14 | hr = '00' 15 | else: 16 | hr = hour 17 | 18 | print hr + ':' + times.group('mm') + ':' + times.group('ss') 19 | 20 | #Using named regex groups 21 | -------------------------------------------------------------------------------- /code-py/reverse_shufle.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isopropylcyanide/Competitive-Programming/cf7dd54728c8e816c78904070b199dd709232e28/code-py/reverse_shufle.py -------------------------------------------------------------------------------- /code-py/scalarProd.py: -------------------------------------------------------------------------------- 1 | 2 | def scalarProd(a): 3 | from collections import Counter 4 | vec = [] 5 | for i in xrange(1, len(a), 2): 6 | vec.append((a[i], a[i - 1])) 7 | 8 | d = Counter(vec) 9 | scalarProdLis = dict() 10 | 11 | for i in vec: 12 | if d[i] > 1: 13 | scalarProdLis[(i[0] * i[0] + i[1] * i[1]) % M] = 0 14 | 15 | vec = list(set(vec)) 16 | 17 | for i in xrange(len(vec)): 18 | for j in xrange(i + 1, len(vec)): 19 | scalarProdLis[( 20 | (vec[i][0] * vec[j][0] + vec[i][1] * vec[j][1]) % M)] = 0 21 | 22 | print len(scalarProdLis) % M 23 | 24 | 25 | def gen(): 26 | ans = [0, C] 27 | for i in xrange(2 * N): 28 | ans.append((ans[-2] + ans[-1]) % M) 29 | 30 | scalarProd(ans[2:]) 31 | 32 | if __name__ == '__main__': 33 | C, M, N = map(int, raw_input().split()) 34 | if N == 1: 35 | print 0 36 | else: 37 | gen() 38 | -------------------------------------------------------------------------------- /code-py/seaarasu.py: -------------------------------------------------------------------------------- 1 | from fractions import gcd 2 | import sys 3 | 4 | """ 5 | Sereja has an array A of N positive integers : A[1], A[2], A[3], ... , A[N]. 6 | In a single operation on the array, he performs the following two steps : 7 | Pick two indices i, j s.t. A[i] > A[j] 8 | A[i] -= A[j] 9 | Sereja can apply these operations any number of times (possibly zero), such that the sum of resulting elements 10 | of the array is as small as possible.Help Sereja find this minimum sum 11 | """ 12 | 13 | 14 | def main(): 15 | for _ in xrange(input()): 16 | N = input() 17 | A = map(int, raw_input().split()) 18 | 19 | for i in xrange(1,N): 20 | ans = sys.maxint 21 | j = i-1 22 | temp = 0 23 | if A[i]%A[j] == 0: 24 | temp = A[j] 25 | else: 26 | temp = A[i]%A[j] 27 | 28 | ans = min(ans,temp) 29 | 30 | A[i] = ans 31 | 32 | print sum(A) 33 | 34 | if __name__ == '__main__': 35 | main() 36 | -------------------------------------------------------------------------------- /code-py/senateEvac.py: -------------------------------------------------------------------------------- 1 | 2 | def solve(N, G, test): 3 | print 'Case #%d: ' % (test + 1), 4 | P = [] 5 | for i in xrange(N): 6 | P.append([G[i], chr(i + 65)]) 7 | 8 | P.sort(key=lambda x: -x[0]) 9 | while P[0][0] != 0: 10 | if len(P) > 2 and P[0][0] == P[1][0] == P[2][0] or P[0][0] > P[1][0]: 11 | print P[0][1], 12 | P[0][0] -= 1 13 | 14 | elif P[0][0] == P[1][0]: 15 | print "%c%c" % (P[0][1], P[1][1]), 16 | P[0][0] -= 1 17 | P[1][0] -= 1 18 | 19 | P.sort(key=lambda x: -x[0]) 20 | print 21 | 22 | if __name__ == '__main__': 23 | for _ in xrange(input()): 24 | N = input() 25 | P = map(int, raw_input().split()) 26 | solve(N, P, _) 27 | -------------------------------------------------------------------------------- /code-py/seqlcs.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | def LCS(a, b): 4 | dp = [[0] * (len(b) + 1) for _ in xrange(len(a) + 1)] 5 | for i, x in enumerate(a, 1): 6 | for j, y in enumerate(b, 1): 7 | dp[i][j] = ( 8 | dp[i - 1][j - 1] + 1 if x == y else 9 | max(dp[i][j - 1], dp[i - 1][j])) 10 | return dp[-1][-1] 11 | 12 | for i in xrange(input()): 13 | N,K,L=map(int,raw_input().split()) 14 | lis=map(int,raw_input().split()) 15 | side=[i for i in xrange(1,K+1)] 16 | 17 | ans=0 18 | for i in list(itertools.product(side,repeat=K)): 19 | if LCS(lis,i)==L:ans+=1 20 | print ans 21 | 22 | -------------------------------------------------------------------------------- /code-py/serejaIncr.py: -------------------------------------------------------------------------------- 1 | import bisect 2 | 3 | 4 | def lis(A): 5 | # nlogn 6 | sortedArr = [] 7 | maxVal = None 8 | for i in A: 9 | if maxVal is None: 10 | sortedArr.append(i) 11 | maxVal = i 12 | 13 | elif i > maxVal: 14 | sortedArr.append(i) 15 | maxVal = i 16 | else: 17 | loc = bisect.bisect_left(sortedArr, i) 18 | sortedArr[loc] = i 19 | if loc == len(sortedArr) - 1: 20 | maxVal = i 21 | 22 | return len(sortedArr) 23 | 24 | if __name__ == '__main__': 25 | for _ in xrange(input()): 26 | N, M = map(int, raw_input().split()) 27 | A = map(int, raw_input().split()) 28 | for __ in xrange(M): 29 | l, r = map(int, raw_input().split()) 30 | print lis(A[l - 1: r]) 31 | -------------------------------------------------------------------------------- /code-py/setZero.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | # @param A : tuple of integers 4 | # @return a strings 5 | 6 | def setZeroes(self, A): 7 | row, col = [], [] 8 | for i in xrange(len(A)): 9 | for j in xrange(len(A[i])): 10 | if A[i][j] == 0: 11 | row.append(i) 12 | col.append(j) 13 | 14 | row, col = list(set(row)), list(set(col)) 15 | for i in xrange(len(A)): 16 | if i in row: 17 | A[i] = [0] * len(A[i]) 18 | 19 | for j in xrange(len(A[0])): 20 | if j in col: 21 | for i in xrange(len(A)): 22 | A[i][j] = 0 23 | return A 24 | 25 | 26 | def main(): 27 | r, c = map(int, raw_input().split()) 28 | lis = [] 29 | for i in xrange(r): 30 | lis.append(map(int, raw_input().split())) 31 | s = Solution() 32 | 33 | k = s.setZeroes(lis) 34 | for i in k: 35 | print i 36 | 37 | if __name__ == '__main__': 38 | main() 39 | -------------------------------------------------------------------------------- /code-py/setdiff.py: -------------------------------------------------------------------------------- 1 | import sys #sum of diff in each subset of given set 2 | 3 | t=int(sys.stdin.readline()) 4 | 5 | def expo(a,n,m): 6 | if n==0:return 1 7 | x,y,n1=2,1,n/2 8 | if n&1:y=2 9 | 10 | while n1>0: 11 | x=(x**2)%m 12 | if n1&1: 13 | if y==1:y= x%m 14 | else:y=(y*x)%m 15 | n1/=2 16 | return y 17 | 18 | while t: 19 | n=int(sys.stdin.readline()) 20 | s=map(int,raw_input().split()) 21 | 22 | ans,mod=0,10**9 +7 23 | s=sorted(s) 24 | 25 | for i in xrange(n-1): 26 | for j in xrange(i+1,n): 27 | ans+=((s[j]-s[i])*expo(2,j-i-1,mod))%mod 28 | print ans%mod 29 | t-=1 30 | 31 | -------------------------------------------------------------------------------- /code-py/shareCand.py: -------------------------------------------------------------------------------- 1 | from fractions import gcd 2 | 3 | 4 | def solve(A, B, C, D): 5 | if A == B: 6 | return 0 7 | 8 | curBest, a = abs(A - B), gcd(C, D) 9 | return abs(curBest - int(a * round(curBest * 1.0 / a))) 10 | 11 | if __name__ == '__main__': 12 | for _ in xrange(input()): 13 | A, B, C, D = map(int, raw_input().split()) 14 | print solve(A, B, C, D) 15 | -------------------------------------------------------------------------------- /code-py/sherParen.py: -------------------------------------------------------------------------------- 1 | mod = 10**9 + 7 2 | 3 | 4 | def solve(A, B, N, K): 5 | # if i**a + j ** b % k == 0 for i,j < N 6 | P = [pow(i, A, K) for i in xrange(1, N + 1)] 7 | Q = [pow(j, B, K) for j in xrange(1, N + 1)] 8 | count = 0 9 | for ind, i in enumerate(P): 10 | for indj, j in enumerate(Q): 11 | if ind != indj and (i + j) % K == 0: 12 | count = (count + 1) % mod 13 | 14 | return count % mod 15 | 16 | 17 | if __name__ == '__main__': 18 | for _ in xrange(input()): 19 | A, B, N, K = map(int, raw_input().split()) 20 | print 'Case #%d: %d' % (_ + 1, solve(A, B, N, K)) 21 | -------------------------------------------------------------------------------- /code-py/sherlockHelp.py: -------------------------------------------------------------------------------- 1 | 2 | M = 10 ** 9 + 7 3 | 4 | 5 | def main(): 6 | for _ in xrange(input()): 7 | N, K = map(int, raw_input().split()) 8 | 9 | if K == 1 and N > 1: 10 | print 0 11 | continue 12 | 13 | print (K % M * pow(K - 1, N - 1, M)) % M 14 | 15 | 16 | if __name__ == '__main__': 17 | main() 18 | -------------------------------------------------------------------------------- /code-py/sherlock_beast.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | find the largest Decent Number having N digits. 4 | 5 | A Decent Number has the following properties: 6 | 7 | Its digits can only be 3's and/or 5's. 8 | The number of 3's it contains is divisible by 5. 9 | The number of 5's it contains is divisible by 3. 10 | """ 11 | 12 | 13 | def solve(n): 14 | fives = -1 15 | for f in xrange(n + 1): 16 | if f % 3 == 0 and (n - f) % 5 == 0: 17 | fives = f 18 | 19 | if fives == -1: 20 | print '-1' 21 | else: 22 | print '5' * fives + '3' * (n - fives) 23 | 24 | 25 | def main(): 26 | for _ in xrange(input()): 27 | solve(input()) 28 | 29 | if __name__ == '__main__': 30 | main() 31 | -------------------------------------------------------------------------------- /code-py/shilXor.py: -------------------------------------------------------------------------------- 1 | K = input() 2 | A = list(raw_input()) 3 | N = len(A) 4 | count = 0 5 | 6 | for i in xrange(N - K + 1): 7 | m = set() 8 | m.add(A[i]) 9 | extra = 0 10 | for j in xrange(i + 1, N): 11 | if len(m) == K: 12 | if A[j] in m: 13 | extra += 1 14 | continue 15 | else: 16 | break 17 | else: 18 | m.add(A[j]) 19 | 20 | if len(m) == K: 21 | count += (1 + extra) 22 | 23 | print count 24 | -------------------------------------------------------------------------------- /code-py/sieve_eros.py: -------------------------------------------------------------------------------- 1 | # print primes using sieve of eratosthenes 2 | 3 | 4 | def primes(a, n): 5 | 6 | sieve = [1] * (n + 1) 7 | for p in range(2, n + 1): 8 | if sieve[p]: 9 | if p >= a: 10 | print p, 11 | for i in range(p * p, n + 1, p): 12 | sieve[i] = 0 13 | 14 | 15 | t = int(raw_input()) 16 | 17 | while t: 18 | a, b = map(int, raw_input().split()) 19 | primes(a, b) 20 | t -= 1 21 | print 22 | -------------------------------------------------------------------------------- /code-py/simStrings.py: -------------------------------------------------------------------------------- 1 | 2 | def substr_len(l): 3 | i = 0 4 | while i < n - l + 1: 5 | yield s[i:i + l] 6 | i += 1 7 | 8 | 9 | def parity(s): 10 | c, l = 0, '' 11 | h = {} 12 | for ind, i in enumerate(s): 13 | if i not in h: 14 | h[i] = c 15 | c += 1 16 | l += str(h[i]) 17 | return l 18 | 19 | 20 | if __name__ == '__main__': 21 | n, q = map(int, raw_input().split()) 22 | s = raw_input() 23 | 24 | for _ in xrange(q): 25 | l, r = map(int, raw_input().split()) 26 | l, r = l - 1, r - 1 27 | length = r - l + 1 28 | _s = s[l:r + 1] 29 | 30 | c = 0 31 | for sub in substr_len(length): 32 | if parity(sub) == parity(_s): 33 | c += 1 34 | print c 35 | -------------------------------------------------------------------------------- /code-py/simpPath.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | 4 | def simplifyPath(A): 5 | if A == '': 6 | return '/' 7 | stack, i = [], 0 8 | 9 | while i < len(A): 10 | while i < len(A) and A[i] == '/': 11 | i += 1 12 | if i == len(A): 13 | break 14 | 15 | j = i 16 | while j < len(A) and A[j] != '/': 17 | j += 1 18 | dirName = A[i: j] 19 | 20 | if dirName == '..': 21 | if stack != []: 22 | stack.pop() 23 | 24 | elif dirName == '.': 25 | pass 26 | 27 | else: 28 | stack.append('/' + dirName) 29 | 30 | i = j 31 | 32 | if stack == []: 33 | return '/' 34 | return ''.join(stack) 35 | 36 | 37 | if __name__ == '__main__': 38 | print simplifyPath(sys.argv[1]) 39 | 40 | 41 | # 42 | 43 | 44 | # 45 | -------------------------------------------------------------------------------- /code-py/simpleOne.py: -------------------------------------------------------------------------------- 1 | from fractions import Fraction 2 | mod = 10**9 + 7 3 | 4 | 5 | def egcd(a, b): 6 | x, y, u, v = 0, 1, 1, 0 7 | while a != 0: 8 | q, r = b // a, b % a 9 | m, n = x - u * q, y - v * q 10 | b, a, x, y, u, v = a, r, u, v, m, n 11 | gcd = b 12 | return gcd, x, y 13 | 14 | 15 | def main(): 16 | for _ in xrange(input()): 17 | p, q, n = map(int, raw_input().split()) 18 | f, one = Fraction(p, q), Fraction(1, 1) 19 | cache = [0 for i in xrange(n + 1)] 20 | cache[0], cache[1] = [0, f] 21 | 22 | for i in xrange(2, n + 1): 23 | num = cache[i - 1] + cache[1] 24 | deno = one - (cache[i - 1]) * cache[1] 25 | cache[i] = num / deno 26 | 27 | print egcd(cache[i].denominator, mod)[1] * (cache[i].numerator) % mod 28 | 29 | 30 | if __name__ == '__main__': 31 | main() 32 | -------------------------------------------------------------------------------- /code-py/sort_dec.py: -------------------------------------------------------------------------------- 1 | import sys #sorts number in increasing number 2 | 3 | a=int(raw_input()) 4 | lis=[] 5 | 6 | while a: 7 | x=sys.stdin.readline() 8 | lis.append(x) 9 | a-=1 10 | 11 | lis.sort() 12 | 13 | print ''.join(lis) 14 | -------------------------------------------------------------------------------- /code-py/sortrow.py: -------------------------------------------------------------------------------- 1 | 2 | def cost(L, r, A): 3 | cost = 0 4 | for i in xrange(len(L)): 5 | cost += (L[i][0] - A[i][0])**2 6 | return cost 7 | 8 | if __name__ == '__main__': 9 | N = input() 10 | L = [] 11 | for _ in xrange(N): 12 | A = map(int, raw_input().split()) 13 | L.append(zip(xrange(N), A)) 14 | 15 | for i in xrange(N): 16 | row = L[i] 17 | incSort = sorted(row, key=lambda x: x[1]) 18 | decSort = sorted(row, key=lambda x: -x[1]) 19 | costInc = cost(L[i], i, incSort) 20 | costDec = cost(L[i], i, decSort) 21 | if costInc < costDec: 22 | print ' '.join([str(i[1]) for i in incSort]) 23 | else: 24 | print ' '.join([str(i[1]) for i in decSort]) 25 | -------------------------------------------------------------------------------- /code-py/spiralMsg.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | L = [] 4 | R, C = map(int, raw_input().split()) 5 | for _ in xrange(R): 6 | L.append(list(raw_input())) 7 | 8 | b, t, l, r = R - 1, 0, 0, C - 1 9 | s = "" 10 | 11 | while b >= t and l <= r: 12 | # print leftmost col 13 | for i in xrange(b, t - 1, -1): 14 | s += L[i][l] 15 | l += 1 16 | 17 | # print top row 18 | for i in xrange(l, r + 1): 19 | s += L[t][i] 20 | t += 1 21 | 22 | # print rightmost col 23 | if t > b or l > r: 24 | break 25 | for i in xrange(t, b + 1): 26 | s += L[i][r] 27 | r -= 1 28 | 29 | # print bottommost row 30 | if t > b or l > r: 31 | break 32 | for i in xrange(r, l - 1, -1): 33 | s += L[b][i] 34 | b -= 1 35 | 36 | print sum([1 for i in s.split('#') if i != '']) 37 | -------------------------------------------------------------------------------- /code-py/squareChef.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | if __name__ == '__main__': 4 | for _ in xrange(input()): 5 | N = input() 6 | A = [0] * N 7 | A[N / 2] = 1 8 | num = N 9 | for i in xrange(N / 2): 10 | A[i] = num 11 | num -= 1 12 | 13 | num = 2 14 | for i in xrange(N / 2 + 1, N): 15 | A[i] = num 16 | num += 1 17 | 18 | A = deque(A) 19 | for i in xrange(N): 20 | print ' '.join([str(i) for i in A]) 21 | A.rotate() 22 | -------------------------------------------------------------------------------- /code-py/squareCount.py: -------------------------------------------------------------------------------- 1 | 2 | # Count all posisble squares in a rectangular grid, including diagonal 3 | 4 | mod = 10**9 + 7 5 | 6 | if __name__ == '__main__': 7 | for _ in xrange(input()): 8 | x, y = map(int, raw_input().split()) 9 | x, y = x - 1, y - 1 10 | 11 | n = min(x, y) 12 | ans = (x * y * n * (n + 1) / 2) % mod 13 | ans = (ans - (x + y) * n * (n - 1) * (n + 1) / 3 + mod) % mod 14 | ans = (ans + n * (n - 1) * (n + 1) * (3 * n - 2) / 12) % mod 15 | ans = (ans + 1) % mod 16 | 17 | print 'Case #%d: %d' % (_ + 1, ans % mod) 18 | -------------------------------------------------------------------------------- /code-py/square_subset.py: -------------------------------------------------------------------------------- 1 | from itertools import * 2 | 3 | 4 | def powerset(iterable): 5 | s = list(iterable) 6 | return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1)) 7 | 8 | for _ in xrange(input()): 9 | n = input() 10 | lis = map(int, raw_input().split()) 11 | ans = 0 12 | 13 | for i in powerset(lis): 14 | if i == (): 15 | continue 16 | pro = reduce(lambda x, y: x * y, i) 17 | root = pro ** 0.5 18 | if root == int(root): 19 | ans += 1 20 | 21 | print ans 22 | -------------------------------------------------------------------------------- /code-py/stfm.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from math import factorial 3 | 4 | def look_up(i,n,m): 5 | global temp,k 6 | if i<=0: 7 | return 0 8 | if k[i]!=0: 9 | temp+=k[i] 10 | else: 11 | temp=i*(factorial(i)+n) 12 | k[i]=look_up(i-1,n,m) 13 | temp+=k[i] 14 | 15 | return temp%m 16 | 17 | n,m=map(int,raw_input().split()); 18 | tsum,lis,temp=0,map(int,raw_input().split()),0 19 | 20 | k=[0 for i in range(max(lis)+1)] 21 | k[0],k[1]=0,2%m 22 | 23 | for i in lis: 24 | temp=0 25 | tsum+=look_up(i,n,m) 26 | 27 | print tsum%m 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /code-py/stockMax.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | N, D = map(int, raw_input().split()) 4 | A = map(int, raw_input().split()) 5 | for _ in xrange(D): 6 | P = input() 7 | h = {} 8 | s, e, diff = -1, -1, 10**9 9 | for ind, i in enumerate(A): 10 | h[i] = ind 11 | if i - P in h: 12 | if i in h and h[i - P] != h[i]: 13 | curDiff = abs(h[i - P] - h[i]) 14 | if curDiff < diff: 15 | diff = curDiff 16 | s, e = h[i - P], h[i] 17 | if s == -1: 18 | print -1 19 | else: 20 | print s + 1, e + 1 21 | -------------------------------------------------------------------------------- /code-py/straightQues.py: -------------------------------------------------------------------------------- 1 | 2 | from __future__ import division 3 | 4 | 5 | def matrixSub(n): 6 | totalSubMat = (n * (n + 1) * (2 * n + 1)) // 6 7 | unique = (n * (n + 1) * (n + 1) * (n + 2)) // 12 8 | print "%6d" % (unique // totalSubMat) 9 | 10 | 11 | def main(): 12 | for _ in xrange(input()): 13 | matrixSub(input()) 14 | 15 | if __name__ == '__main__': 16 | main() 17 | -------------------------------------------------------------------------------- /code-py/straight_flush.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/isopropylcyanide/Competitive-Programming/cf7dd54728c8e816c78904070b199dd709232e28/code-py/straight_flush.py -------------------------------------------------------------------------------- /code-py/strq.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import string 3 | 4 | lis=map(str,raw_input().split()) 5 | lis=str(lis) 6 | q=int(raw_input()) 7 | 8 | def cstr(a,b,l,r): 9 | global lis 10 | count =0 11 | for i in xrange(l,r+1): 12 | for j in xrange(i+1,r+2): 13 | if lis[i]==a and lis[j]==b: 14 | count+=1 15 | return count 16 | 17 | while q: 18 | a,b,l,r=raw_input().split() 19 | a,b,l,r=str(a),str(b),int(l),int(r) 20 | print cstr(a,b,l,r) 21 | 22 | q-=1 23 | 24 | -------------------------------------------------------------------------------- /code-py/subArrayProd.py: -------------------------------------------------------------------------------- 1 | 2 | mod = 10**9 + 7 3 | 4 | 5 | def modInv(N): 6 | return pow(N, mod - 2, mod) 7 | 8 | if __name__ == '__main__': 9 | N = input() 10 | A = [1] 11 | for i in xrange(N): 12 | A.append(input()) 13 | A[-1] = (A[-1] * A[-2]) % mod 14 | 15 | for _ in xrange(input()): 16 | l, r = map(int, raw_input().split()) 17 | print (A[r] * modInv(A[l - 1])) % mod 18 | -------------------------------------------------------------------------------- /code-py/subsets.py: -------------------------------------------------------------------------------- 1 | 2 | class Solution: 3 | # @param A : list of integers 4 | # @return a list of list of integers 5 | """Given a collection of integers that might contain duplicates, S, return all possible subsets.""" 6 | 7 | def subsetsWithDup(self, A): 8 | def subsetsUtil(i, s): 9 | if i == len(A): 10 | L.add(tuple(sorted(s))) 11 | s = [] 12 | return 13 | 14 | b = s[:] 15 | subsetsUtil(i + 1, b + [A[i]]) 16 | subsetsUtil(i + 1, b) 17 | 18 | L = set() 19 | subsetsUtil(0, []) 20 | L = sorted([list(i) for i in L]) 21 | return L 22 | 23 | if __name__ == '__main__': 24 | a = Solution().subsetsWithDup(map(int, raw_input().split())) 25 | for i in a: 26 | print i 27 | -------------------------------------------------------------------------------- /code-py/substrConcat.py: -------------------------------------------------------------------------------- 1 | class Solution: 2 | # @param A : string 3 | # @param B : tuple of strings 4 | # @return a list of integers 5 | 6 | def findSubstring(self, A, B): 7 | if B == []: 8 | return [] 9 | 10 | hDic, n, m = {}, len(B), len(B[0]) 11 | for i in B: 12 | hDic[str(i)] = 1 13 | ans = [] 14 | 15 | for i in xrange(len(A) - m * n + 1): 16 | h = {k: v for k, v in hDic.items()} 17 | for j in xrange(n): 18 | s = str(A[i + j * m: i + j * m + m]) 19 | if s in h: 20 | if h[s] == 1: 21 | h.pop(s) 22 | else: 23 | h[s] = 0 24 | else: 25 | break 26 | 27 | if len(h) == 0: 28 | ans.append(i) 29 | return ans 30 | 31 | if __name__ == '__main__': 32 | print Solution().findSubstring(raw_input(), raw_input().split()) 33 | -------------------------------------------------------------------------------- /code-py/sumPieces.py: -------------------------------------------------------------------------------- 1 | mod = 10**9 + 7 2 | 3 | 4 | def solve(A, N): 5 | W, val = 0, 0 6 | lim = N / 2 if N % 2 == 0 else N / 2 + 1 7 | for i in xrange(lim): 8 | if i == 0: 9 | val = (val + pow(2, N, mod) - 1 + mod) % mod 10 | W = (W + (A[i] * val) % mod) % mod 11 | W = (W + (A[N - 1 - i] * val) % mod) % mod 12 | else: 13 | val = (val + pow(2, N - 1 - i, mod) - pow(2, i - 1) + mod) % mod 14 | W = (W + (A[i] * val) % mod) % mod 15 | if i != N - 1 - i: 16 | W = (W + (A[N - 1 - i] * val) % mod) % mod 17 | return W % mod 18 | 19 | if __name__ == '__main__': 20 | N = input() 21 | A = map(int, raw_input().split()) 22 | print solve(A, N) 23 | -------------------------------------------------------------------------------- /code-py/sum_is_mul.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def main(): 4 | for _ in xrange(input()): 5 | N = input() 6 | A = map(int, raw_input().split()) 7 | count = 0 8 | 9 | for i in xrange(N): 10 | for j in xrange(i, N): 11 | mul = reduce(lambda x, y: x * y, A[i:j + 1]) 12 | if mul == sum(A[i:j + 1]): 13 | count += 1 14 | 15 | print count 16 | 17 | if __name__ == '__main__': 18 | main() 19 | -------------------------------------------------------------------------------- /code-py/superValid.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | for _ in xrange(input()): 4 | N, K = map(int, raw_input().split()) 5 | if N % 2 == 1: 6 | print 0 7 | else: 8 | print N / K - 1 9 | -------------------------------------------------------------------------------- /code-py/swap-case.py: -------------------------------------------------------------------------------- 1 | 2 | S=map(str,raw_input().strip()); 3 | length=len(S) 4 | 5 | correct=[0 for i in xrange(length)] 6 | for index,i in enumerate(S): 7 | if i.isupper():S[index]=i.lower() 8 | elif i.islower():S[index]=i.upper() 9 | 10 | print ''.join(S) 11 | -------------------------------------------------------------------------------- /code-py/talazy.py: -------------------------------------------------------------------------------- 1 | 2 | def solve(N, A): 3 | if N == 2: 4 | return min(A) 5 | diff = A[1] - A[0] 6 | thold = 0 7 | curRemoval = 10**9 8 | 9 | D = [] 10 | for i in xrange(N - 1): 11 | D.append(A[i + 1] - A[i]) 12 | 13 | d = A[1] - A[0] 14 | for i in xrange(1, N): 15 | cur = A[i + 1] - A[i] 16 | 17 | print D 18 | 19 | if __name__ == '__main__': 20 | for _ in xrange(input()): 21 | N = input() 22 | A = map(int, raw_input().split()) 23 | print solve(N, A) 24 | -------------------------------------------------------------------------------- /code-py/taskSched.py: -------------------------------------------------------------------------------- 1 | def schedule_brute(tasks): 2 | sched = [] 3 | tasks.sort(key=lambda x: x[1]) 4 | 5 | # print 'Sorted: ', tasks 6 | start, cur, = 0, 0 7 | max_over = float('-inf') 8 | 9 | for task in tasks: 10 | st = cur 11 | et = cur + task[2] # minutes reqd 12 | 13 | sched.append((task[0], st, et)) 14 | cur += task[2] 15 | 16 | if et - task[1] > max_over: 17 | max_over = et - task[1] 18 | 19 | return (max_over, sched) 20 | 21 | 22 | def main(): 23 | tasks = [] 24 | min_dead = [] 25 | 26 | for _ in xrange(input()): 27 | d, m = map(int, raw_input().split()) 28 | tasks.append((_, d, m)) 29 | 30 | maxover, sched = schedule_brute(tasks) 31 | min_dead.append((maxover, sched,)) 32 | 33 | for i in min_dead: 34 | print i[0] 35 | 36 | if __name__ == '__main__': 37 | main() 38 | -------------------------------------------------------------------------------- /code-py/tdriver.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | t=int(sys.stdin.readline()) 4 | 5 | while t: 6 | n=int(sys.stdin.readline()) 7 | a,b=map(int,raw_input().split()) 8 | 9 | v=[[1 for i in xrange(n)] for i in xrange(n)] 10 | x,y=[],[] 11 | while n: 12 | c,d=raw_input().split() 13 | x.extend(c) 14 | y.extend(d) 15 | n-=1 16 | 17 | x=[int(i) for i in x] 18 | y=[int(i) for i in y] 19 | maxm=0 20 | 21 | for i in xrange(len(x)): 22 | for j in xrange(len(x)): 23 | if i==j:continue 24 | 25 | if v[i][j]==1 and v[j][i]==1: 26 | 27 | maxm+=max(a*abs(x[i]-x[j]), b*abs(y[i]-y[j])) 28 | v[i][j],v[j][i]=0,0 29 | print maxm 30 | -------------------------------------------------------------------------------- /code-py/testgen.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | if __name__ == '__main__': 5 | # T = random.randrange(1, 10) 6 | T = 10 7 | print T 8 | for i in xrange(T): 9 | # N = random.randrange(1, pow(10, 5)) 10 | N = pow(10, 5) 11 | print N 12 | for _ in xrange(N): 13 | A = random.randrange(pow(10, 6), pow(10, 7)) 14 | print A, 15 | -------------------------------------------------------------------------------- /code-py/trainPartner.py: -------------------------------------------------------------------------------- 1 | 2 | m = {1: (4, 'LB'), 3 | 2: (5, 'MB'), 4 | 3: (6, 'UB'), 5 | 4: (1, 'LB'), 6 | 5: (2, 'MB'), 7 | 6: (3, 'UB'), 8 | 7: (8, 'SU'), 9 | 8: (7, 'SL') 10 | } 11 | 12 | if __name__ == '__main__': 13 | for _ in xrange(input()): 14 | N = input() 15 | N -= 1 16 | block, N = N / 8, N % 8 + 1 17 | part, val = m[N] 18 | print '%d%s' % (part + 8 * block, val) 19 | -------------------------------------------------------------------------------- /code-py/transformAB.py: -------------------------------------------------------------------------------- 1 | 2 | P = [] 3 | primes = [] 4 | MAX = 10**6 + 5 5 | 6 | 7 | def sieve(): 8 | global P 9 | P = [1] * (MAX) 10 | P[0] = P[1] = 0 11 | 12 | for i in xrange(2, MAX): 13 | if P[i] == 1: 14 | primes.append(i) 15 | for j in xrange(i * i, MAX, i): 16 | P[j] = 0 17 | del(P) 18 | 19 | if __name__ == '__main__': 20 | sieve() 21 | A, B = map(int, raw_input().split()) 22 | if (B - A) in primes: 23 | print '%s->%d' % (A, B) 24 | else: 25 | print 'Unlucky Benny' 26 | -------------------------------------------------------------------------------- /code-py/tricoin.py: -------------------------------------------------------------------------------- 1 | from math import floor 2 | 3 | 4 | def f(k): 5 | return int(floor(0.5 * ((pow(8 * k + 1, 0.5) - 1)))) 6 | 7 | if __name__ == '__main__': 8 | for _ in xrange(input()): 9 | print f(input()) 10 | -------------------------------------------------------------------------------- /code-py/twoChar.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | from itertools import combinations as ce 3 | 4 | 5 | def isValidString(L): 6 | # Returns true if a string consists of alternating char 7 | if len(L) < 2: 8 | return False 9 | f, s = L[0], L[1] 10 | for ind, i in enumerate(L[2:]): 11 | if ind % 2 == 0 and i != f: 12 | return False 13 | if ind % 2 == 1 and i != s: 14 | return False 15 | 16 | return True 17 | 18 | 19 | def solve(d, s): 20 | if len(d) == 1: 21 | return 0 22 | maxLen = 0 23 | for i in ce(d.iterkeys(), len(d) - 2): 24 | L = [k for k in s if k not in i] 25 | if isValidString(L): 26 | maxLen = max(maxLen, len(L)) 27 | 28 | return maxLen 29 | 30 | 31 | if __name__ == '__main__': 32 | N = input() 33 | s = raw_input() 34 | d = Counter(s) 35 | print solve(d, s) 36 | -------------------------------------------------------------------------------- /code-py/twostr.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | for i in xrange(input()): 4 | A = raw_input() 5 | B = raw_input() 6 | 7 | A, B = list(A), list(B) 8 | for i in xrange(len(B)): 9 | if B[i] == '?' and A[i] != '?': 10 | B[i] = A[i] 11 | elif B[i] == '?' and A[i] == '?': 12 | B[i] = 'z' 13 | 14 | A, B = ''.join(A), ''.join(B) 15 | A = A.replace('?', '[a-z]+') 16 | 17 | pattern = re.compile(A) 18 | if pattern.match(B)is not None: 19 | print 'Yes' 20 | else: 21 | print 'No' 22 | -------------------------------------------------------------------------------- /code-py/vCake.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def dio(N, C): 4 | if N % 2 == 0: 5 | t = (2 * C) / N 6 | if (2 * C) % N != 0: 7 | return "No" 8 | elif t >= 2 * N: 9 | return "Yes" 10 | elif t >= N + 1 and t % 2 != 0: 11 | return "Yes" 12 | else: 13 | return "No" 14 | else: 15 | t = C / N 16 | if C % N != 0: 17 | return "No" 18 | elif t >= (N + 1) / 2: 19 | return "Yes" 20 | else: 21 | return "No" 22 | 23 | if __name__ == '__main__': 24 | for _ in xrange(input()): 25 | N, C = map(int, raw_input().split()) 26 | print dio(N, C) 27 | -------------------------------------------------------------------------------- /code-py/vcs.py: -------------------------------------------------------------------------------- 1 | import sys 2 | t=int(sys.stdin.readline()) 3 | 4 | while t: 5 | n,m,k=[int(i) for i in raw_input().split()] 6 | A=map(int,raw_input().split()) 7 | B=map(int,raw_input().split()) 8 | 9 | print len(list(set(A) & set (B))), 10 | print len(set(xrange(1,n+1))-set(A) & set(xrange(1,n+1))-set(B)) 11 | 12 | t-=1 13 | -------------------------------------------------------------------------------- /code-py/vibhuPair.py: -------------------------------------------------------------------------------- 1 | 2 | mod = 10**9 + 7 3 | MAX = 10**6 + 5 4 | 5 | 6 | def precompute(A): 7 | for i in xrange(2, MAX): 8 | A[i] = (A[i - 1] + A[i - 2] * (i - 1)) % mod 9 | 10 | if __name__ == '__main__': 11 | A = [1] * MAX 12 | precompute(A) 13 | for _ in xrange(input()): 14 | print A[input()] 15 | -------------------------------------------------------------------------------- /code-py/votersToWin.py: -------------------------------------------------------------------------------- 1 | 2 | def main(): 3 | for _ in range(int(input())): 4 | A = list(map(int, input().split()))[1:] 5 | minPostsNeeded = len(A) - 1 6 | 7 | for i in range(len(A) - 2, -1, -1): 8 | if A[i] != 0: 9 | minPostsNeeded -= A[i] 10 | if minPostsNeeded <= 0: 11 | print ('Able to satisfy in front. Setting min to ', i) 12 | minPostsNeeded = i 13 | print ('minPosts ', minPostsNeeded, ' i ', i, ' A[i] ', A[i]) 14 | print (minPostsNeeded) 15 | 16 | 17 | if __name__ == "__main__": 18 | main() 19 | -------------------------------------------------------------------------------- /code-py/warehouse.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | N, C = map(int, raw_input().split()) 4 | L = [] 5 | for _ in xrange(C): 6 | u, v = map(int, raw_input().split()) 7 | L.append([u, v]) 8 | 9 | L.sort(key=lambda x: -x[1]) 10 | ans, mb = 0, 0 11 | for i in L: 12 | if mb >= N: 13 | break 14 | else: 15 | mbox = min(i[0], N - mb) 16 | ans += i[1] * mbox 17 | mb += mbox 18 | # print mbox, ans, mb 19 | print ans 20 | -------------------------------------------------------------------------------- /code-py/watsum.py: -------------------------------------------------------------------------------- 1 | 2 | if __name__ == '__main__': 3 | for _ in xrange(input()): 4 | d = input() 5 | n = len(str(d)) 6 | print d % 10 + n 7 | -------------------------------------------------------------------------------- /code-py/wayout.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import operator 3 | from math import log 4 | 5 | def get_min(hashmap,N,H): 6 | sum_map=sum(hashmap) 7 | min_map=min(hashmap) 8 | 9 | if H==1: 10 | return min_map 11 | elif H==N: 12 | return sum_map 13 | else: 14 | min_count,starter=sum_map,N-1 15 | 16 | while starter!=H-2: 17 | total=0 18 | for i in xrange(starter,starter-H,-1): 19 | total+=hashmap[i] 20 | 21 | if total>1 12 | else: 13 | print -1 14 | -------------------------------------------------------------------------------- /code-py/xorsub.py: -------------------------------------------------------------------------------- 1 | a=int(raw_input()) 2 | 3 | while 1<=a<=10: 4 | n,k=map(int,raw_input().split()) 5 | 6 | lis=[] 7 | lis=map(int,raw_input().split()) 8 | 9 | counter,tem=0,0 10 | print lis 11 | 12 | temp=[[0 for x in range(n)]for x in range(2**n)] 13 | 14 | for counter in range(2**n): 15 | for j in range(n): 16 | if counter & 1<