├── .gitignore ├── Contests ├── ClistCalendar.png ├── Other Solutions │ ├── BattleCode │ │ ├── 2018 │ │ │ ├── Attackable.java │ │ │ ├── CumSum.java │ │ │ ├── Globals.java │ │ │ ├── HealthComparator.java │ │ │ ├── MapLocationComparator.java │ │ │ ├── Movable.java │ │ │ ├── PiiComparator.java │ │ │ ├── Player.java │ │ │ ├── Structure.java │ │ │ ├── Test.java │ │ │ ├── UnitComparator.java │ │ │ ├── WorkerComparator.java │ │ │ ├── botHealer.java │ │ │ ├── botKnight.java │ │ │ ├── botMage.java │ │ │ ├── botRanger.java │ │ │ ├── botWorker.java │ │ │ ├── fastGC.java │ │ │ ├── genBFS.java │ │ │ ├── pii.java │ │ │ ├── run.bat │ │ │ ├── run.sh │ │ │ ├── structFactory.java │ │ │ └── structRocket.java │ │ └── 2019 │ │ │ ├── Action2.java │ │ │ ├── Attackable.java │ │ │ ├── Building.java │ │ │ ├── Castle.java │ │ │ ├── Church.java │ │ │ ├── Consts.java │ │ │ ├── Crusader.java │ │ │ ├── Movable.java │ │ │ ├── MyRobot.java │ │ │ ├── Pilgrim.java │ │ │ ├── Preacher.java │ │ │ ├── Prophet.java │ │ │ ├── Robot2.java │ │ │ ├── bfsMap.java │ │ │ ├── moveMap.java │ │ │ ├── pi.java │ │ │ ├── safeMap.java │ │ │ ├── secretMap.java │ │ │ └── unitCounter.java │ ├── UCF HSPT │ │ ├── 2016 │ │ │ ├── UCF HSPT 16 - hyenas.cpp │ │ │ ├── UCF HSPT 16 - keyboard.cpp │ │ │ ├── UCF HSPT 16 - mazes.cpp │ │ │ ├── UCF HSPT 16 - perfect.cpp │ │ │ ├── UCF HSPT 16 - sandwich.cpp │ │ │ ├── UCF HSPT 16 - shapes.cpp │ │ │ ├── UCF HSPT 16 - squircle.cpp │ │ │ └── UCF HSPT 16 - stacks.cpp │ │ ├── 2017 │ │ │ ├── UCF HSPT 17 - coins.cpp │ │ │ ├── UCF HSPT 17 - dinner.cpp │ │ │ ├── UCF HSPT 17 - elemental.cpp │ │ │ ├── UCF HSPT 17 - lerps.cpp │ │ │ ├── UCF HSPT 17 - multiply.cpp │ │ │ ├── UCF HSPT 17 - optimal.cpp │ │ │ ├── UCF HSPT 17 - unite.cpp │ │ │ └── UCF HSPT 17 - wipeout.cpp │ │ └── 2018 │ │ │ ├── colony.cpp │ │ │ ├── even.cpp │ │ │ ├── expansion.cpp │ │ │ ├── fire.cpp │ │ │ ├── fireworks.cpp │ │ │ ├── flooding.cpp │ │ │ ├── laptop.cpp │ │ │ ├── lights.cpp │ │ │ ├── nails.cpp │ │ │ ├── poker.cpp │ │ │ └── slayer.cpp │ └── VT HSPC │ │ └── 2017 │ │ ├── Coconut.cpp │ │ ├── Code.cpp │ │ ├── Criss-Cross.cpp │ │ ├── Difficulty Order.md │ │ ├── Monk.cpp │ │ ├── Provinces.cpp │ │ ├── RA Duty.cpp │ │ ├── Saving.cpp │ │ ├── Shiritori.cpp │ │ ├── Stopcard.cpp │ │ ├── Swish.cpp │ │ ├── Through.cpp │ │ └── Weight.cpp ├── Tools │ ├── CF │ │ ├── cf.py │ │ ├── cf_probs.py │ │ ├── cf_subs.py │ │ └── grader.py │ ├── Other │ │ ├── checker.py │ │ ├── grader.sh │ │ ├── interactive_runner.py │ │ ├── ioi_probs.py │ │ └── topcoder_probs.py │ ├── README.md │ └── USACO │ │ ├── camper_format.cpp │ │ ├── usaco_gen.cpp │ │ ├── usaco_probs.py │ │ ├── usaco_results.js │ │ ├── usaco_val_camp.cpp │ │ └── usaco_val_monthly.cpp ├── USACO Links │ ├── Division-Specific │ │ ├── Bronze.md │ │ ├── Gold.md │ │ ├── Old Gold.md │ │ ├── Platinum.md │ │ └── Silver.md │ ├── README.md │ ├── Table Formatter.cpp │ ├── USACO Stats.txt │ └── USACO Topics.md ├── USACO Solutions │ ├── 2007-08 │ │ ├── alake.cpp │ │ ├── bales.cpp │ │ ├── bclgold.cpp │ │ ├── gourmet.cpp │ │ ├── nabor.cpp │ │ ├── pieface.cpp │ │ └── treasure.cpp │ ├── 2008-09 │ │ ├── cheer.cpp │ │ ├── cleanup.cpp │ │ ├── damage.cpp │ │ ├── damage2.cpp │ │ ├── job.cpp │ │ ├── lfence.cpp │ │ ├── tower2.cpp │ │ └── toys.cpp │ ├── 2009-10 │ │ ├── allow.cpp │ │ ├── balloc.cpp │ │ ├── cookie.cpp │ │ ├── diet4.cpp │ │ ├── hop.cpp │ │ ├── island2.cpp │ │ ├── rocks.cpp │ │ ├── starc.cpp │ │ ├── telephone.cpp │ │ └── vidgame.cpp │ ├── 2010-11 │ │ ├── bottleneck.cpp │ │ ├── cowpic.cpp │ │ ├── exercise3.cpp │ │ ├── gdisc.cpp │ │ ├── letter.cpp │ │ ├── lostcows.cpp │ │ ├── mkmoney.cpp │ │ ├── soda.cpp │ │ └── solder.cpp │ ├── 2011-12 │ │ ├── Dec │ │ │ ├── 11 Dec G1.cpp │ │ │ ├── 11 Dec G2.cpp │ │ │ └── 11 Dec G3.cpp │ │ ├── Feb │ │ │ ├── 12 Feb G1.cpp │ │ │ ├── 12 Feb G2.cpp │ │ │ └── 12 Feb G3.cpp │ │ ├── Jan │ │ │ ├── 12 Jan G1.cpp │ │ │ ├── 12 Jan G2.cpp │ │ │ └── 12 Jan G3.cpp │ │ ├── Mar │ │ │ ├── 12 Mar G1.cpp │ │ │ ├── 12 Mar G2.cpp │ │ │ ├── 12 Mar G3.cpp │ │ │ └── 12 Mar S3.cpp │ │ ├── Nov │ │ │ ├── 11 Nov G1.cpp │ │ │ └── 11 Nov G2.cpp │ │ ├── Open │ │ │ ├── 12 Open G1.cpp │ │ │ ├── 12 Open G2.cpp │ │ │ └── 12 Open G3.cpp │ │ └── stack.cpp │ ├── 2012-13 │ │ ├── Dec 2012 │ │ │ ├── 12 Dec G1.cpp │ │ │ ├── 12 Dec G2.cpp │ │ │ └── 12 Dec G3.cpp │ │ ├── Feb 2013 │ │ │ ├── 13 Feb G1.cpp │ │ │ ├── 13 Feb G2.cpp │ │ │ └── 13 Feb G3.cpp │ │ ├── Jan 2013 │ │ │ ├── 13 Jan G1.cpp │ │ │ ├── 13 Jan G2.cpp │ │ │ └── 13 Jan G3.cpp │ │ ├── March 2013 │ │ │ ├── 13 Mar G1.cpp │ │ │ ├── 13 Mar G2.cpp │ │ │ └── 13 Mar G3.cpp │ │ ├── Nov 2012 │ │ │ ├── 12 Nov G1.cpp │ │ │ ├── 12 Nov G2.cpp │ │ │ └── 12 Nov G3.cpp │ │ └── Open 2013 │ │ │ ├── 13 Open G1.cpp │ │ │ ├── 13 Open G2.cpp │ │ │ └── 13 Open G3.cpp │ ├── 2013-14 │ │ ├── Dec 2013 │ │ │ ├── 13 Dec G1.cpp │ │ │ ├── 13 Dec G2.cpp │ │ │ └── 13 Dec G3.cpp │ │ ├── Feb 2014 │ │ │ ├── 14 Feb G1.cpp │ │ │ ├── 14 Feb G2.cpp │ │ │ └── 14 Feb G3.cpp │ │ ├── Jan 2014 │ │ │ ├── 14 Jan G1.cpp │ │ │ ├── 14 Jan G2.cpp │ │ │ └── 14 Jan G3.cpp │ │ ├── Mar 2014 │ │ │ ├── 14 Mar G1.cpp │ │ │ ├── 14 Mar G2.cpp │ │ │ └── 14 Mar G3.cpp │ │ ├── Nov 2013 │ │ │ ├── 13 Nov G1.cpp │ │ │ ├── 13 Nov G2.cpp │ │ │ └── 13 Nov G3.cpp │ │ └── Open 2014 │ │ │ ├── 14 Open G1.cpp │ │ │ ├── 14 Open G2.cpp │ │ │ ├── 14 Open G3 (9-10).cpp │ │ │ └── 14 Open G3 (Model).cpp │ ├── 2014-15 │ │ ├── Dec 2014 Gold │ │ │ ├── 14 Dec G1.cpp │ │ │ ├── 14 Dec G2.cpp │ │ │ └── 14 Dec G3.cpp │ │ ├── Feb 2015 │ │ │ ├── Feb 2015 Gold │ │ │ │ ├── 15 Feb G1.cpp │ │ │ │ ├── 15 Feb G2.cpp │ │ │ │ └── 15 Feb G3.cpp │ │ │ └── Feb 2015 Silver │ │ │ │ └── 15 Feb S3.cpp │ │ ├── Jan 2015 Gold │ │ │ ├── 15 Jan G1.cpp │ │ │ ├── 15 Jan G2.cpp │ │ │ └── 15 Jan G3.cpp │ │ └── Open 2015 Gold │ │ │ ├── 15 Open G1.cpp │ │ │ ├── 15 Open G2.cpp │ │ │ └── 15 Open G3.cpp │ ├── 2015-16 │ │ ├── Dec 2015 │ │ │ ├── Bronze │ │ │ │ ├── 15 Dec B1.cpp │ │ │ │ ├── 15 Dec B2.cpp │ │ │ │ └── 15 Dec B3.cpp │ │ │ ├── Gold │ │ │ │ ├── 15 Dec G1.cpp │ │ │ │ ├── 15 Dec G2.cpp │ │ │ │ └── 15 Dec G3.cpp │ │ │ ├── Plat │ │ │ │ ├── 15 Dec P1.cpp │ │ │ │ ├── 15 Dec P2 (SegTree).cpp │ │ │ │ ├── 15 Dec P2 (Set).cpp │ │ │ │ └── 15 Dec P3.cpp │ │ │ └── Silver │ │ │ │ ├── 15 Dec S1.cpp │ │ │ │ ├── 15 Dec S2.cpp │ │ │ │ └── 15 Dec S3.cpp │ │ ├── Feb 2016 │ │ │ ├── Bronze │ │ │ │ ├── 16 Feb B1.cpp │ │ │ │ ├── 16 Feb B2.cpp │ │ │ │ └── 16 Feb B3.cpp │ │ │ ├── Gold │ │ │ │ └── 16 Feb G1.cpp │ │ │ ├── Plat │ │ │ │ ├── 16 Feb P1.cpp │ │ │ │ ├── 16 Feb P2.cpp │ │ │ │ ├── cbarn_dc.cpp │ │ │ │ ├── cbarn_lc.cpp │ │ │ │ └── cbarn_lc_deque.cpp │ │ │ └── Silver │ │ │ │ ├── 16 Feb S1.cpp │ │ │ │ └── 16 Feb S3.cpp │ │ ├── Jan 2016 │ │ │ ├── Bronze │ │ │ │ ├── 16 Jan B1.cpp │ │ │ │ ├── 16 Jan B2.cpp │ │ │ │ └── 16 Jan B3.cpp │ │ │ ├── Gold │ │ │ │ ├── 16 Jan G1 (Binary Search).cpp │ │ │ │ ├── 16 Jan G1.cpp │ │ │ │ ├── 16 Jan G2.cpp │ │ │ │ ├── 16 Jan G3.cpp │ │ │ │ └── lightsout.cpp │ │ │ ├── Plat │ │ │ │ ├── 16 Jan P1.cpp │ │ │ │ ├── 16 Jan P2.cpp │ │ │ │ └── 16 Jan P3.cpp │ │ │ └── Silver │ │ │ │ ├── 16 Jan S1.cpp │ │ │ │ ├── 16 Jan S2.cpp │ │ │ │ └── 16 Jan S3.cpp │ │ └── Open 2016 │ │ │ ├── Bronze │ │ │ ├── 16 Open B1.cpp │ │ │ └── 16 Open B2.cpp │ │ │ ├── Gold │ │ │ ├── 16 Open G1.cpp │ │ │ ├── 16 Open G2.cpp │ │ │ └── 16 Open G3.cpp │ │ │ ├── Plat │ │ │ ├── 262144.cpp │ │ │ ├── 262144_new.cpp │ │ │ ├── bcs.cpp │ │ │ ├── bcs_editorial.cpp │ │ │ ├── landscape_deque.cpp │ │ │ ├── landscape_dp.cpp │ │ │ └── landscape_pq.cpp │ │ │ └── Silver │ │ │ ├── 16 Open S1.cpp │ │ │ ├── 16 Open S2.cpp │ │ │ └── 16 Open S3.cpp │ ├── 2016-17 │ │ ├── Dec 2016 │ │ │ ├── Bronze │ │ │ │ ├── 16 Dec B1.cpp │ │ │ │ ├── 16 Dec B2.cpp │ │ │ │ └── 16 Dec B3.cpp │ │ │ ├── Gold │ │ │ │ ├── 16 Dec G1.cpp │ │ │ │ ├── 16 Dec G2.cpp │ │ │ │ └── 16 Dec G3.cpp │ │ │ ├── Plat │ │ │ │ ├── 16 Dec P2.cpp │ │ │ │ ├── roboherd.cpp │ │ │ │ ├── roboherd_slow.cpp │ │ │ │ ├── triangles.cpp │ │ │ │ └── triangles_bitset.cpp │ │ │ └── Silver │ │ │ │ ├── 16 Dec S1.cpp │ │ │ │ ├── 16 Dec S2.cpp │ │ │ │ └── 16 Dec S3.cpp │ │ ├── Feb 2017 │ │ │ ├── Bronze │ │ │ │ ├── 17 Feb B1.cpp │ │ │ │ ├── 17 Feb B2.cpp │ │ │ │ └── 17 Feb B3.cpp │ │ │ ├── Gold │ │ │ │ ├── 17 Feb G1.cpp │ │ │ │ └── 17 Feb G3.cpp │ │ │ ├── Plat │ │ │ │ ├── 17 Feb P1 (BIT).cpp │ │ │ │ ├── 17 Feb P1 (Set).cpp │ │ │ │ ├── 17 Feb P2 (Brute Force).cpp │ │ │ │ ├── 17 Feb P2 (Segtree).cpp │ │ │ │ ├── 17 Feb P3 (Segtree).cpp │ │ │ │ └── 17 Feb P3 (Set).cpp │ │ │ └── Silver │ │ │ │ ├── 17 Feb S1.cpp │ │ │ │ ├── 17 Feb S2.cpp │ │ │ │ └── 17 Feb S3.cpp │ │ ├── Jan 2017 │ │ │ ├── Bronze │ │ │ │ ├── 17 Jan B1.cpp │ │ │ │ ├── 17 Jan B2.cpp │ │ │ │ └── 17 Jan B3.cpp │ │ │ ├── Gold │ │ │ │ ├── 17 Jan G1.cpp │ │ │ │ ├── 17 Jan G2.cpp │ │ │ │ └── 17 Jan G3.cpp │ │ │ ├── Plat │ │ │ │ ├── 17 Jan P1.cpp │ │ │ │ ├── 17 Jan P2.cpp │ │ │ │ ├── promo.cpp │ │ │ │ ├── subrev.cpp │ │ │ │ └── subrev_old.cpp │ │ │ └── Silver │ │ │ │ ├── 17 Jan S1.cpp │ │ │ │ ├── 17 Jan S2.cpp │ │ │ │ └── 17 Jan S3.cpp │ │ └── Open 2017 │ │ │ ├── Bronze │ │ │ ├── 17 Open B1.cpp │ │ │ ├── 17 Open B2.cpp │ │ │ └── 17 Open B3.cpp │ │ │ ├── Gold │ │ │ ├── 17 Open G2.cpp │ │ │ └── 17 Open G3.cpp │ │ │ ├── Plat │ │ │ ├── art.cpp │ │ │ ├── cowbasic.cpp │ │ │ ├── grass.cpp │ │ │ ├── grass_fake.cpp │ │ │ └── grass_recent.cpp │ │ │ └── Silver │ │ │ ├── 17 Open S1.cpp │ │ │ ├── 17 Open S2.cpp │ │ │ └── 17 Open S3.cpp │ ├── 2017-18 │ │ ├── Dec 2017 │ │ │ ├── Gold │ │ │ │ ├── 17 Dec Gold 1.cpp │ │ │ │ ├── 17 Dec Gold 2.cpp │ │ │ │ └── 17 Dec Gold 3.cpp │ │ │ ├── Plat │ │ │ │ ├── 17 Dec Plat 2.cpp │ │ │ │ ├── 17 Dec Plat 3.cpp │ │ │ │ ├── sa_automaton_2.cpp │ │ │ │ ├── standingout_automaton.cpp │ │ │ │ ├── standingout_hash.cpp │ │ │ │ └── standingout_sa.cpp │ │ │ └── Silver │ │ │ │ ├── 17 Dec Silver 1.cpp │ │ │ │ ├── 17 Dec Silver 2.cpp │ │ │ │ └── 17 Dec Silver 3.cpp │ │ ├── Feb 2018 │ │ │ ├── Gold │ │ │ │ ├── dirtraverse.cpp │ │ │ │ ├── snowboots.cpp │ │ │ │ └── taming.cpp │ │ │ └── Plat │ │ │ │ ├── gymnast.cpp │ │ │ │ ├── newbarn.cpp │ │ │ │ └── slingshot.cpp │ │ ├── Jan 2018 │ │ │ ├── Gold │ │ │ │ ├── 18 Jan Gold 1.cpp │ │ │ │ └── 18 Jan Gold 3.cpp │ │ │ ├── Plat │ │ │ │ ├── atlarge_cd.cpp │ │ │ │ ├── atlarge_nlogn.cpp │ │ │ │ ├── atlarge_nsqrtn.cpp │ │ │ │ ├── atlarge_nsqrtn?.cpp │ │ │ │ ├── lifeguards _simpler.cpp │ │ │ │ ├── lifeguards.cpp │ │ │ │ └── sprinklers.cpp │ │ │ └── Silver │ │ │ │ ├── 18 Jan Silver 1.cpp │ │ │ │ └── 18 Jan Silver 2.cpp │ │ └── Open 2018 │ │ │ ├── Gold │ │ │ ├── milkorder.cpp │ │ │ ├── sort.cpp │ │ │ ├── sort_bin.cpp │ │ │ └── talent.cpp │ │ │ └── Plat │ │ │ ├── disrupt.cpp │ │ │ ├── sort.cpp │ │ │ ├── sort_ez.cpp │ │ │ └── train.cpp │ ├── 2018-19 │ │ ├── Dec 2018 │ │ │ ├── Gold │ │ │ │ ├── cowpatibility.cpp │ │ │ │ ├── cowpatibility_bitset.cpp │ │ │ │ ├── dining.cpp │ │ │ │ └── teamwork.cpp │ │ │ ├── Plat │ │ │ │ ├── balance.cpp │ │ │ │ ├── gathering.cpp │ │ │ │ └── itout.cpp │ │ │ └── Silver │ │ │ │ ├── convention.cpp │ │ │ │ ├── convention2.cpp │ │ │ │ └── mooyomooyo.cpp │ │ ├── Feb 2019 │ │ │ ├── Gold │ │ │ │ ├── cowland.cpp │ │ │ │ ├── dishes.cpp │ │ │ │ └── paintbarn.cpp │ │ │ └── Plat │ │ │ │ ├── cowdate.cpp │ │ │ │ ├── mooriokart.cpp │ │ │ │ ├── mowing (nlogn).cpp │ │ │ │ └── mowing.cpp │ │ ├── Jan 2019 │ │ │ ├── Gold │ │ │ │ ├── poetry.cpp │ │ │ │ ├── poetry.java │ │ │ │ ├── poetry_slow.cpp │ │ │ │ ├── shortcut.cpp │ │ │ │ ├── shortcut.java │ │ │ │ ├── sleepy.cpp │ │ │ │ └── sleepy.java │ │ │ ├── Plat │ │ │ │ ├── exercise.cpp │ │ │ │ ├── redistricting (SegTree).cpp │ │ │ │ ├── redistricting.cpp │ │ │ │ └── tracking2.cpp │ │ │ └── Silver │ │ │ │ ├── mountains.cpp │ │ │ │ ├── perimeter.cpp │ │ │ │ └── planting.cpp │ │ └── Open 2019 │ │ │ ├── Gold │ │ │ ├── balance.cpp │ │ │ ├── snakes (senpat).java │ │ │ ├── snakes.cpp │ │ │ ├── walk (12:15).cpp │ │ │ ├── walk (13:15).cpp │ │ │ ├── walk (senpat).cpp │ │ │ └── walk.cpp │ │ │ ├── Plat │ │ │ ├── escape (TLE).cpp │ │ │ ├── escape.cpp │ │ │ ├── treeboxes.cpp │ │ │ ├── valleys (simpler).cpp │ │ │ └── valleys.cpp │ │ │ └── cowjump.cpp │ ├── 2019-20 │ │ ├── Dec │ │ │ ├── Bronze │ │ │ │ ├── gymnastics.cpp │ │ │ │ ├── livestock (np).cpp │ │ │ │ ├── livestock.cpp │ │ │ │ └── whereami.cpp │ │ │ ├── Gold │ │ │ │ ├── milkvisits.cpp │ │ │ │ ├── milkvisits_online.cpp │ │ │ │ ├── moortal.cpp │ │ │ │ └── pump.cpp │ │ │ ├── Plat │ │ │ │ ├── pieaters.cpp │ │ │ │ ├── snowcow.cpp │ │ │ │ └── treedepth.cpp │ │ │ └── Silver │ │ │ │ ├── meetings.cpp │ │ │ │ ├── milkvisits.cpp │ │ │ │ └── moobuzz.cpp │ │ ├── Feb │ │ │ ├── Bronze │ │ │ │ ├── breedflip.cpp │ │ │ │ ├── swap.cpp │ │ │ │ └── tri_n^2.cpp │ │ │ ├── Gold │ │ │ │ ├── deleg.cpp │ │ │ │ ├── help.cpp │ │ │ │ └── timeline.cpp │ │ │ ├── Plat │ │ │ │ ├── deleg_plat.cpp │ │ │ │ ├── help_NKlogN+K^2.cpp │ │ │ │ ├── help_NKlogN+NK^2.cpp │ │ │ │ └── triangles.cpp │ │ │ └── Silver │ │ │ │ ├── clock.cpp │ │ │ │ ├── swap_bin.cpp │ │ │ │ ├── swap_cycles.cpp │ │ │ │ └── tri_silv.cpp │ │ ├── Jan │ │ │ ├── Bronze │ │ │ │ ├── photo_O(N).cpp │ │ │ │ ├── race.cpp │ │ │ │ ├── word.cpp │ │ │ │ └── word_dhruv.py │ │ │ ├── Gold │ │ │ │ ├── boards.cpp │ │ │ │ ├── threesum.java │ │ │ │ └── time.cpp │ │ │ ├── Plat │ │ │ │ ├── cave.cpp │ │ │ │ ├── falling.cpp │ │ │ │ ├── nondec_divide.cpp │ │ │ │ └── nondec_matrix.cpp │ │ │ └── Silver │ │ │ │ ├── berry_N*max.cpp │ │ │ │ ├── loan.cpp │ │ │ │ ├── worm.py │ │ │ │ ├── worm2.py │ │ │ │ ├── wormsort.java │ │ │ │ ├── wormsort_binsearch.cpp │ │ │ │ └── wormsort_merging.cpp │ │ └── Open │ │ │ ├── Bronze │ │ │ ├── socdist1.cpp │ │ │ ├── socdist2.cpp │ │ │ └── tracing.cpp │ │ │ ├── Gold │ │ │ ├── exercise.cpp │ │ │ ├── fcolor.cpp │ │ │ └── haircut.cpp │ │ │ ├── Plat │ │ │ ├── circus.cpp │ │ │ ├── ex_plat.cpp │ │ │ ├── exercise_3000_dwr.cpp │ │ │ ├── exercise_50.cpp │ │ │ ├── exercise_500.cpp │ │ │ └── sprinklers2.cpp │ │ │ └── Silver │ │ │ ├── cereal.cpp │ │ │ ├── moop.cpp │ │ │ └── socdist.cpp │ └── 2020-21 │ │ └── Dec │ │ ├── Bronze │ │ ├── abc.py │ │ ├── daisy.cpp │ │ ├── rut_bronze.cpp │ │ ├── rut_bronze_brian_1.cpp │ │ └── rut_bronze_brian_2.cpp │ │ ├── Gold │ │ ├── genomics.cpp │ │ ├── genomics_N2.cpp │ │ ├── rep.cpp │ │ └── sp.cpp │ │ ├── Plat │ │ ├── cowmistry.cpp │ │ ├── sleeping.cpp │ │ ├── space.cpp │ │ └── space_matrix.cpp │ │ └── Silver │ │ ├── rp.cpp │ │ ├── rut_silver.cpp │ │ └── sickcow.cpp └── USACO Training │ ├── Ch 1 │ ├── 1.1 beads.cpp │ ├── 1.1 friday.cpp │ ├── 1.1 gift1.cpp │ ├── 1.1 ride.cpp │ ├── 1.2 dualpal.cpp │ ├── 1.2 milk2.cpp │ ├── 1.2 namenum.cpp │ ├── 1.2 palsquare.cpp │ ├── 1.3 wormholes.cpp │ ├── 1.4 ariprog.cpp │ ├── 1.5 pprime.cpp │ └── 1.5 sprime.cpp │ ├── Ch 2 │ ├── 2.1 castle.cpp │ ├── 2.1 frac1.cpp │ ├── 2.1 holstein.cpp │ ├── 2.3 nocows.cpp │ └── 2.3 prefix.cpp │ ├── Ch 3 │ ├── 3.1 agrinet.cpp │ ├── 3.2 msquare.cpp │ ├── 3.3 camelot (bad).cpp │ ├── 3.3 camelot.cpp │ └── 3.3 range.cpp │ ├── Ch 4 │ ├── 4.1 fence6.cpp │ ├── 4.2 ditch.cpp │ ├── 4.2 job.cpp │ ├── 4.2 stall4.cpp │ ├── 4.3 buylow.cpp │ └── 4.4 milk6.cpp │ ├── Ch 5 │ ├── 5.1 fc.cpp │ ├── 5.2 snail.cpp │ ├── 5.3 bigbrn.cpp │ ├── 5.3 milk4.cpp │ ├── 5.3 schlnet.cpp │ ├── 5.5 hidden.cpp │ ├── 5.5 picture.cpp │ └── 5.5 twofive.cpp │ ├── Ch 6 │ ├── 6.1 cowxor.cpp │ ├── 6.1 vans.cpp │ ├── 6.2 calfflac.cpp │ ├── 6.2 packrec.cpp │ ├── 6.2 rect1.cpp │ ├── 6.3 cowcycle.cpp │ ├── 6.3 cryptcow.cpp │ ├── 6.3 fence8.cpp │ ├── 6.4 fence3.cpp │ ├── 6.4 prime3.cpp │ ├── 6.4 wissqu.cpp │ ├── 6.5 betsy.cpp │ ├── 6.5 checker.cpp │ ├── 6.5 clocks.cpp │ ├── 6.5 fence4.cpp │ └── 6.5 latin.cpp │ └── README.md ├── Implementations ├── CP Guide Contents.pdf ├── Makefile ├── README.md ├── content │ ├── combinatorial (11.2) │ │ ├── DeBruijnSeq.h │ │ ├── IntPerm.h │ │ ├── MatroidIsect.h │ │ ├── MatroidPart.h │ │ ├── NimProduct.h │ │ ├── PermGroup.h │ │ ├── README.md │ │ ├── RSK.h │ │ ├── RSKrecover.h │ │ ├── chapter.tex │ │ ├── factorial.tex │ │ ├── matroidIsect_Old.h │ │ ├── rskverify │ │ └── rskverify.cpp │ ├── contest │ │ ├── .bashrc │ │ ├── .vimrc │ │ ├── CppIO.h │ │ ├── FastScanner.java │ │ ├── README.md │ │ ├── Snippets.md │ │ ├── TemplateLong.cpp │ │ ├── TemplateLong_Old.cpp │ │ ├── TemplateMinimal.cpp │ │ ├── TemplateShort.cpp │ │ ├── chapter.tex │ │ ├── cppIO_old.h │ │ ├── genLong.py │ │ ├── hash.sh │ │ ├── makeSnip.py │ │ ├── old │ │ │ ├── CppIO_test.cpp │ │ │ ├── TemplateLong_Old.cpp │ │ │ ├── TemplateShort.cpp │ │ │ ├── cppIO_older.h │ │ │ ├── fstTrue_test.cpp │ │ │ ├── genShort.py │ │ │ ├── templateOld.cpp │ │ │ ├── templateTest.cpp │ │ │ └── template_usaco_guide.cpp │ │ ├── stress.sh │ │ ├── template.cpp │ │ ├── templateKACTL.cpp │ │ ├── troubleshoot.tex │ │ └── troubleshoot.txt │ ├── data-structures │ │ ├── 1D Range Queries (9.2) │ │ │ ├── BIT.h │ │ │ ├── BIToff.h │ │ │ ├── BITrange.h │ │ │ ├── BitNd.h │ │ │ ├── ConsecutivePairs.h │ │ │ ├── LazySegAlt.h │ │ │ ├── LazySegmentTree (15.2).h │ │ │ ├── LichaoSeg.h │ │ │ ├── MaxQuery.h │ │ │ ├── Mo (15.1).h │ │ │ ├── PSeg (15.2).h │ │ │ ├── PermTree.h │ │ │ ├── RectUnion.h │ │ │ ├── SegTreeBeats.h │ │ │ ├── SegmentTree (9.2).h │ │ │ ├── SparseSeg (9.2).h │ │ │ ├── Wavelet.h │ │ │ ├── pseg1.h │ │ │ ├── pseg2.h │ │ │ └── psegTesting.cpp │ │ ├── 2D Range Queries (15.2) │ │ │ ├── BIT2DOff (15.2).h │ │ │ ├── BITseg (15.2).h │ │ │ ├── BITtree (15.2).h │ │ │ ├── SegSeg (15.2).h │ │ │ ├── friendcross.cpp │ │ │ └── mowing.cpp │ │ ├── DynaCon.h │ │ ├── EulerTourTree.h │ │ ├── LeftistHeap.h │ │ ├── README.md │ │ ├── STL (5) │ │ │ ├── Bset.h │ │ │ ├── CoordCompress.h │ │ │ ├── HashMap.h │ │ │ ├── HashMapSmall.h │ │ │ ├── LineContainer.h │ │ │ ├── LineContainerDeque.h │ │ │ ├── LineContainerNew.h │ │ │ ├── MapComparator (5.2).h │ │ │ ├── MinDeque (8.2).h │ │ │ ├── OrderStatisticTree.h │ │ │ ├── PQ.h │ │ │ ├── Rope.h │ │ │ ├── bset_test.cpp │ │ │ ├── hashmap_old.h │ │ │ └── rope_test.cpp │ │ ├── Static Range Queries (9.1) │ │ │ ├── FasterRMQ.h │ │ │ ├── PrefixSums (9.1).h │ │ │ ├── RMQ (9.1).h │ │ │ └── RangeQuery.h │ │ ├── Treap (15.3).h │ │ └── chapter.tex │ ├── geometry (13) │ │ ├── 3D │ │ │ ├── Hull3D.h │ │ │ ├── Hull3D_kactl.h │ │ │ ├── Point3D.h │ │ │ ├── PolySaVol.h │ │ │ ├── Quater.h │ │ │ └── death_conveyor.cpp │ │ ├── Circles │ │ │ ├── Circle.h │ │ │ ├── CircleIsect.h │ │ │ ├── CircleTangents.h │ │ │ ├── Circumcenter.h │ │ │ └── MinEnclosingCirc.h │ │ ├── Misc │ │ │ ├── ClosestPair (13.2).h │ │ │ ├── Delaunay3.h │ │ │ ├── DelaunayFast.h │ │ │ ├── DelaunayIncremental.h │ │ │ ├── KDtree.h │ │ │ ├── ManhattanMST.h │ │ │ ├── MaxCollinear.h │ │ │ └── kdtree_KACTL.h │ │ ├── Polygons │ │ │ ├── ConvexHull (13.2).h │ │ │ ├── ConvexHullGraham.h │ │ │ ├── HalfPlaneIsect.h │ │ │ ├── HalfPlaneSet.h │ │ │ ├── HullDiameter.h │ │ │ ├── HullTangents.h │ │ │ ├── HullTangentsTest.cpp │ │ │ ├── InPolygon.h │ │ │ ├── LineHull.h │ │ │ ├── LineHullTest.cpp │ │ │ ├── MinkowskiSum.h │ │ │ ├── PolygonCenArea.h │ │ │ ├── PolygonUnion.java │ │ │ ├── PolygonUnion.kt │ │ │ └── _old_HalfPlaneIsect.h │ │ ├── Primitives │ │ │ ├── AngleCmp.h │ │ │ ├── Complex.h │ │ │ ├── ComplexComp.h │ │ │ ├── Point.h │ │ │ ├── PointShort.h │ │ │ ├── SegDist.h │ │ │ └── SegIsect.h │ │ ├── README.md │ │ └── chapter.tex │ ├── graphs (12) │ │ ├── Advanced │ │ │ ├── ChordalGraphRecognition.h │ │ │ ├── DMOJdynamicTreeTest.cpp │ │ │ ├── DirectedMST.h │ │ │ ├── DirectedMST_KACTL.h │ │ │ ├── DirectedMSTtest.cpp │ │ │ ├── DominatorTree.h │ │ │ ├── EdgeColor.h │ │ │ ├── EdgeColorBip.h │ │ │ ├── KthWalk.h │ │ │ ├── LCT.h │ │ │ ├── LCTtest.cpp │ │ │ ├── LoopyNim.h │ │ │ ├── MaxClique.h │ │ │ ├── StableRoommates.h │ │ │ ├── ThreeEdgeCC.h │ │ │ ├── TopTree.h │ │ │ ├── TreeDecomp2.h │ │ │ └── maxCliqueTesting.cpp │ │ ├── Basics │ │ │ ├── BellmanFord (7.3).h │ │ │ ├── Dijkstra (7.3).h │ │ │ ├── DirectedCycle.h │ │ │ ├── FloydWarshall (7.3).h │ │ │ ├── GridBFS (7.2).h │ │ │ ├── NegativeCycle (7.3).h │ │ │ ├── TopoSort (7.4).h │ │ │ └── TreeTour (7.2).h │ │ ├── DFS │ │ │ ├── BCC (12.4).h │ │ │ ├── BipolarOrientation.h │ │ │ ├── EulerPath (12.2).h │ │ │ ├── MaximalCliques.h │ │ │ ├── SCCK.h │ │ │ ├── SCCT.h │ │ │ └── TwoSAT (12.1).h │ │ ├── DSU │ │ │ ├── DSU (7.6).h │ │ │ ├── DSUrb (15.5).h │ │ │ ├── DynaCon.h │ │ │ └── TwoEdgeCC.h │ │ ├── Flows (12.3) │ │ │ ├── CapacityScaling.h │ │ │ ├── Dinic.h │ │ │ ├── GlobalMinCut.h │ │ │ ├── GomoryHu.h │ │ │ ├── HLPP.h │ │ │ ├── MCMF.h │ │ │ ├── NetworkSimplex.h │ │ │ └── README.md │ │ ├── Matching │ │ │ ├── DFSmatch.h │ │ │ ├── FakeMatch.h │ │ │ ├── GeneralMatchBlossom.h │ │ │ ├── GeneralMatchBlossom_Alt.h │ │ │ ├── GeneralMatchBlossom_Old.h │ │ │ ├── GeneralMatchDet.h │ │ │ ├── GeneralWeightedMatch.h │ │ │ ├── Hungarian.h │ │ │ ├── MaxMatchFast.h │ │ │ ├── MaxMatchHeuristic.h │ │ │ └── MaxMatchLexMin.h │ │ ├── README.md │ │ ├── Trees (10) │ │ │ ├── Centroid (10.3).h │ │ │ ├── HLD (10.3).h │ │ │ ├── LCAjump (10.2).h │ │ │ ├── LCArmq (10.2).h │ │ │ ├── README.md │ │ │ ├── SmallToLarge (10.2).h │ │ │ ├── TreeDiameter (10.1).h │ │ │ └── lcajump_old.h │ │ └── chapter.tex │ ├── math │ │ ├── chapter.tex │ │ └── sphericalCoordinates.pdf │ ├── number-theory (11.1) │ │ ├── Euclid │ │ │ ├── CRT.h │ │ │ ├── Euclid.h │ │ │ ├── FracInterval.h │ │ │ ├── ModArith.h │ │ │ └── modArithBrute.cpp │ │ ├── Modular Arithmetic │ │ │ ├── DiscreteLog.h │ │ │ ├── FastMod.h │ │ │ ├── ModFact.h │ │ │ ├── ModFactInt.h │ │ │ ├── ModInt.h │ │ │ ├── ModInt128.h │ │ │ ├── ModIntDynamic.h │ │ │ ├── ModIntShort.h │ │ │ ├── ModIntShort_Old.h │ │ │ ├── ModMulLL.h │ │ │ ├── ModSqrt.h │ │ │ ├── ModSqrtExplan.tex │ │ │ ├── ModSum.h │ │ │ ├── ModSumExplan.tex │ │ │ └── Order.h │ │ ├── Primality │ │ │ ├── FactorBasic.h │ │ │ ├── FactorFast.h │ │ │ ├── MillerRabin.h │ │ │ ├── MultiplicativePrefixSums.h │ │ │ ├── MultiplicativePrefix_Old.h │ │ │ ├── PrimeCnt.h │ │ │ ├── PrimeCntMin25.h │ │ │ ├── PrimeCntNeal.h │ │ │ ├── Sieve.h │ │ │ ├── factorOld.h │ │ │ ├── factorOld2.h │ │ │ └── primeCntOld.h │ │ └── chapter.tex │ ├── numerical │ │ ├── Arithmetic │ │ │ ├── BigInt.h │ │ │ ├── ExprParse.h │ │ │ ├── Frac.h │ │ │ └── bigint_old.h │ │ ├── Matrix (11.3) │ │ │ ├── CharPoly.h │ │ │ ├── Hafnian.h │ │ │ ├── Matrix.h │ │ │ ├── MatrixInv.h │ │ │ ├── MatrixTree.h │ │ │ ├── ShermanMorrison.h │ │ │ ├── SparseDet.h │ │ │ ├── XorBasis.h │ │ │ └── matrix_old.h │ │ ├── Misc │ │ │ ├── GoldenSectionSearch.h │ │ │ ├── Integrate.h │ │ │ ├── IntegrateAdaptive.h │ │ │ ├── LinRec2.h │ │ │ ├── LinearRecurrence.h │ │ │ └── Simplex.h │ │ ├── Polynomials │ │ │ ├── ChirpZ.h │ │ │ ├── FFT.h │ │ │ ├── Karatsuba.h │ │ │ ├── Poly.h │ │ │ ├── PolyConv.h │ │ │ ├── PolyEuclid.h │ │ │ ├── PolyInterpolate.h │ │ │ ├── PolyInv.h │ │ │ ├── PolyInvSimpler.h │ │ │ ├── PolyMultipoint.h │ │ │ ├── PolyRoots.h │ │ │ ├── fft_old.h │ │ │ └── fftmod_old.h │ │ ├── README.md │ │ └── chapter.tex │ ├── strings (14) │ │ ├── Heavy │ │ │ ├── PalTree.h │ │ │ ├── SuffixAutomaton.h │ │ │ ├── SuffixTree.h │ │ │ ├── paltree_old.h │ │ │ └── suffixTree_kactl.h │ │ ├── Light │ │ │ ├── AhoCorasickFixed.h │ │ │ ├── AhoCorasickUnfixed.h │ │ │ ├── HashRange (14.2).h │ │ │ ├── KMP.h │ │ │ ├── LyndonFactor.h │ │ │ ├── Manacher.h │ │ │ ├── MinRotation.h │ │ │ ├── ReverseBW (14.4).h │ │ │ ├── SuffixArray (14.4).h │ │ │ ├── SuffixArrayLinear.h │ │ │ ├── SuffixArrayTest.cpp │ │ │ ├── TandemRepeats.h │ │ │ ├── Trie (14.1).h │ │ │ ├── TrieAlpha.h │ │ │ ├── Z (14.3).h │ │ │ └── tandemRepeats_old.h │ │ └── chapter.tex │ ├── test-session │ │ ├── chapter.tex │ │ └── test-session.tex │ ├── tex │ │ ├── kactl.tex │ │ ├── kactlpkg.sty │ │ ├── mit.png │ │ └── preprocessor.py │ └── various │ │ ├── BIT.kt │ │ ├── BumpAllocator.h │ │ ├── BumpAllocatorSTL.h │ │ ├── CircularLCS.h │ │ ├── Decimal.py │ │ ├── DynaLIS.h │ │ ├── FastIO.h │ │ ├── Knapsack.h │ │ ├── Kotlin.kt │ │ ├── Main.java │ │ ├── Ops.h │ │ ├── Python3.py │ │ ├── SMAWK.h │ │ ├── SmallPtr.h │ │ ├── Ycombinator.h │ │ ├── chapter.tex │ │ ├── kotlinOld.kt │ │ └── ktLinks.txt ├── kactl.pdf ├── kactl_color.pdf ├── test-compiles.sh ├── test-session.pdf └── testAll.py ├── LICENSE ├── Other Implementations ├── 04 - Sorting and Searching │ ├── Binary Search (4.3).cpp │ ├── Coordinate Compression.cpp │ ├── Interval Cover (4.1).cpp │ ├── README.md │ └── Ternary Search (8.3).cpp ├── 06 - DP │ ├── Distinct Subsequences (6).cpp │ ├── Divide And Conquer (15.4).cpp │ ├── HamilPath (12.2).cpp │ ├── Knapsack (6).cpp │ ├── LCS (6).cpp │ ├── LIS (6).cpp │ ├── README.md │ └── SOS (15.5).cpp └── Additional.md ├── README.md └── Resources ├── Competition Math.md ├── Questions.md ├── Solving Problems.md └── old_README.md /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | header.tmp 3 | a.out 4 | /Implementations/build/ 5 | Implementations/kactl.pdf 6 | .vscode -------------------------------------------------------------------------------- /Contests/ClistCalendar.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bqi343/cp-notebook/292c614b7b83c355b188234966b3b336bc009f16/Contests/ClistCalendar.png -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2018/HealthComparator.java: -------------------------------------------------------------------------------- 1 | import bc.*; 2 | import java.util.*; 3 | 4 | public class HealthComparator extends Globals implements Comparator { 5 | public static int getHeat(Unit U) { 6 | if (fastGC.isStructure(U)) return INF; 7 | return (int)U.health(); 8 | } 9 | public int compare(Unit c1, Unit c2) { 10 | int a = getHeat(c1); 11 | int b = getHeat(c2); 12 | if (a < b) return -1; 13 | if (a > b) return 1; 14 | return 0; 15 | } 16 | } -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2018/MapLocationComparator.java: -------------------------------------------------------------------------------- 1 | import bc.*; 2 | import java.util.*; 3 | 4 | public class MapLocationComparator extends Globals implements Comparator { 5 | public int compare(MapLocation A, MapLocation B) { 6 | int a = karboniteCount[A.getX()][A.getY()]; 7 | int b = karboniteCount[B.getX()][B.getY()]; 8 | if (a < b) return -1; 9 | if (a > b) return 1; 10 | return 0; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2018/PiiComparator.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class PiiComparator extends Globals implements Comparator { 4 | public int compare(pii A, pii B) { 5 | int a = karboniteCount[A.f][A.s]; 6 | int b = karboniteCount[B.f][B.s]; 7 | if (a < b) return -1; 8 | if (a > b) return 1; 9 | return 0; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2018/WorkerComparator.java: -------------------------------------------------------------------------------- 1 | import bc.*; 2 | import java.util.*; 3 | 4 | public class WorkerComparator extends Globals implements Comparator { 5 | int getVal(Unit U) { 6 | if(C.getWidth() * C.getHeight() <= 900) { 7 | return -toPii(U).distanceSquaredTo(get(U,closeStructure)); 8 | } 9 | return toPii(U).distanceSquaredTo(get(U,closeStructure)); 10 | } 11 | 12 | public int compare(Unit c1, Unit c2) { 13 | return Integer.valueOf(getVal(c1)).compareTo(getVal(c2)); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2018/pii.java: -------------------------------------------------------------------------------- 1 | import bc.*; 2 | 3 | public class pii extends Globals implements Comparable { 4 | static int distanceSquaredTo(Unit a, pii b) { 5 | return toPii(a).distanceSquaredTo(b); 6 | } 7 | 8 | public int f, s; 9 | pii(int F, int S) { 10 | f = F; 11 | s = S; 12 | } 13 | int distanceSquaredTo(pii b) { 14 | if (b == null) return INF; 15 | return (f-b.f)*(f-b.f)+(s-b.s)*(s-b.s); 16 | } 17 | pii add(int d) { 18 | return new pii (f+xdir[d],s+ydir[d]); 19 | } 20 | 21 | public boolean equals(pii x) { 22 | if (x == null) return false; 23 | return f == x.f && s == x.s; 24 | } 25 | 26 | public int compareTo(pii x) { 27 | if (f != x.f) return Integer.valueOf(f).compareTo(x.f); 28 | return Integer.valueOf(s).compareTo(x.s); 29 | } 30 | 31 | /*public int compareTo(pii x) { 32 | if (f != x.f) { 33 | if (f < x.f) return -1; 34 | if (f > x.f) return 1; 35 | return 0; 36 | } 37 | if (s < x.s) return -1; 38 | if (s > x.s) return 1; 39 | return 0; 40 | if (karboniteCount[f][s] < karboniteCount[x.f][x.s]) return -1; 41 | if (karboniteCount[f][s] > karboniteCount[x.f][x.s]) return 1; 42 | return 0; 43 | }*/ 44 | } 45 | -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2018/run.bat: -------------------------------------------------------------------------------- 1 | rem This file should build and run your code. 2 | rem It will only run if you're in nodocker mode on a windows machine. 3 | 4 | echo Java currently doesn't work on Windows without docker. Please use python or run docker. 5 | exit 1 -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2018/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | # This file should build and run your code. 3 | # It will run if you're in nodocker mode on Mac or Linux, 4 | # or if you're running in docker. 5 | 6 | # Compile our code. 7 | echo javac $(find . -name '*.java') -classpath ../battlecode/java 8 | javac $(find . -name '*.java') -classpath ../battlecode/java 9 | 10 | # Run our code. 11 | echo java -classpath .:../battlecode/java Player 12 | java -classpath .:../battlecode/java Player 13 | -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2019/Action2.java: -------------------------------------------------------------------------------- 1 | package bc19; 2 | 3 | import java.util.*; 4 | import java.math.*; 5 | 6 | import static bc19.Consts.*; 7 | 8 | public class Action2 { 9 | int type = -1, dx = -1, dy = -1, karb = -1, fuel = -1, unit = -1; 10 | } 11 | -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2019/Crusader.java: -------------------------------------------------------------------------------- 1 | package bc19; 2 | 3 | import static bc19.Consts.*; 4 | 5 | public class Crusader extends Attackable { 6 | public Crusader(MyRobot z) { super(z); } 7 | Action2 run() { 8 | return runDefault(); 9 | /*Z.sendToCastle(); 10 | Action2 A = react(); 11 | if (A != null) { 12 | Z.log("REACT (" +Z.CUR.x+", "+Z.CUR.y+") "+A.type+" "+A.dx+" "+A.dy); 13 | return A; 14 | } 15 | Z.log("PATROL (" +Z.CUR.x+", "+Z.CUR.y+")"); 16 | return patrol();*/ 17 | // return aggressive(); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2019/Preacher.java: -------------------------------------------------------------------------------- 1 | package bc19; 2 | 3 | import static bc19.Consts.*; 4 | 5 | public class Preacher extends Attackable { 6 | public Preacher(MyRobot z) { super(z); } 7 | Action2 run() { 8 | // Z.dumpCastles(); 9 | return runDefault(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2019/Prophet.java: -------------------------------------------------------------------------------- 1 | package bc19; 2 | 3 | import static bc19.Consts.*; 4 | 5 | public class Prophet extends Attackable { 6 | public Prophet(MyRobot z) { super(z); } 7 | Action2 run() { return runDefault(); } 8 | } 9 | -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2019/bfsMap.java: -------------------------------------------------------------------------------- 1 | package bc19; 2 | 3 | import java.util.*; 4 | import java.math.*; 5 | 6 | import static bc19.Consts.*; 7 | 8 | public class bfsMap extends moveMap { 9 | public bfsMap(MyRobot Z, int mx) { super(Z,mx); } 10 | boolean ok(int x, int y) { 11 | return Z.passable(x,y); 12 | // return true; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2019/pi.java: -------------------------------------------------------------------------------- 1 | package bc19; 2 | 3 | import java.util.*; 4 | import java.math.*; 5 | 6 | import static bc19.Consts.*; 7 | 8 | public class pi { 9 | public int f, s; 10 | pi(int _f, int _s) { 11 | f = _f; s = _s; 12 | } 13 | int norm() { 14 | return f*f+s*s; 15 | } 16 | int euclidDist(pi b) { 17 | if (b == null || f == -1 || b.f == -1) return MOD; 18 | return (f-b.f)*(f-b.f)+(s-b.s)*(s-b.s); 19 | } 20 | public boolean equals(pi x) { 21 | if (x == null) return false; 22 | return f == x.f && s == x.s; 23 | } 24 | public String toString() { 25 | return "("+f+", "+s+")"; 26 | } 27 | /*public int compareTo(pi x) { 28 | if (f != x.f) return Integer.valueOf(f).compareTo(x.f); 29 | return Integer.valueOf(s).compareTo(x.s); 30 | }*/ 31 | }; 32 | -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2019/safeMap.java: -------------------------------------------------------------------------------- 1 | package bc19; 2 | 3 | import java.util.*; 4 | import java.math.*; 5 | 6 | import static bc19.Consts.*; 7 | 8 | public class safeMap extends moveMap { 9 | public safeMap(MyRobot Z, int mx) { super(Z,mx); } 10 | boolean ok(int x, int y) { 11 | return Z.passable(x,y) && Z.danger[y][x] == 0; 12 | // return true; 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Contests/Other Solutions/BattleCode/2019/secretMap.java: -------------------------------------------------------------------------------- 1 | package bc19; 2 | 3 | import java.util.*; 4 | import java.math.*; 5 | 6 | import static bc19.Consts.*; 7 | 8 | public class secretMap extends moveMap { 9 | public secretMap(MyRobot Z) { 10 | super(Z,2); dirs.clear(); 11 | for (int i = 0; i < 8; ++i) dirs.add(new pi(smDX[i],smDY[i])); 12 | } 13 | boolean ok(int x, int y) { 14 | return Z.passable(x,y); 15 | // return true; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Contests/Other Solutions/UCF HSPT/2016/UCF HSPT 16 - hyenas.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | using namespace __gnu_pbds; 7 | 8 | typedef long long ll; 9 | typedef vector vi; 10 | typedef pair pi; 11 | template using Tree = tree, rb_tree_tag,tree_order_statistics_node_update>; 12 | 13 | #define FOR(i, a, b) for (int i=a; i<(b); i++) 14 | #define F0R(i, a) for (int i=0; i<(a); i++) 15 | #define FORd(i,a,b) for (int i = (b)-1; i >= a; i--) 16 | #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) 17 | 18 | #define sz(x) (int)(x).size() 19 | #define mp make_pair 20 | #define pb push_back 21 | #define f first 22 | #define s second 23 | #define lb lower_bound 24 | #define ub upper_bound 25 | 26 | const int MOD = 1000000007; 27 | 28 | int main() { 29 | ios_base::sync_with_stdio(0);cin.tie(0); 30 | int n; cin >> n; 31 | F0R(i,n) { 32 | int r,c; cin >> r >> c; 33 | int ans = 0; 34 | F0R(j,r) F0R(k,c) { 35 | char x; cin >> x; 36 | if (x == 'H') ans++; 37 | } 38 | cout << "Location #" << (i+1) << ": " << ans << "\n"; 39 | } 40 | } 41 | 42 | // read! 43 | // ll vs. int! 44 | -------------------------------------------------------------------------------- /Contests/Other Solutions/UCF HSPT/2016/UCF HSPT 16 - shapes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | using namespace __gnu_pbds; 7 | 8 | typedef long long ll; 9 | typedef vector vi; 10 | typedef pair pi; 11 | template using Tree = tree, rb_tree_tag,tree_order_statistics_node_update>; 12 | 13 | #define FOR(i, a, b) for (int i=a; i<(b); i++) 14 | #define F0R(i, a) for (int i=0; i<(a); i++) 15 | #define FORd(i,a,b) for (int i = (b)-1; i >= a; i--) 16 | #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) 17 | 18 | #define sz(x) (int)(x).size() 19 | #define mp make_pair 20 | #define pb push_back 21 | #define f first 22 | #define s second 23 | #define lb lower_bound 24 | #define ub upper_bound 25 | 26 | const int MOD = 1000000007; 27 | 28 | int n; 29 | 30 | int main() { 31 | ios_base::sync_with_stdio(0);cin.tie(0); 32 | cin >> n; 33 | FOR(i,1,n+1) { 34 | cout << "Shape #" << i << ": "; 35 | int m; cin >> m; 36 | if (m == 3 || m == 4) cout << "Johnny's favorite!"; 37 | else cout << "Johnny will not be pleased with this one."; 38 | cout << "\n"; 39 | } 40 | } 41 | 42 | // read! 43 | // ll vs. int! 44 | -------------------------------------------------------------------------------- /Contests/Other Solutions/UCF HSPT/2017/UCF HSPT 17 - multiply.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | using namespace __gnu_pbds; 7 | 8 | typedef long long ll; 9 | typedef vector vi; 10 | typedef pair pi; 11 | template using Tree = tree, rb_tree_tag,tree_order_statistics_node_update>; 12 | 13 | #define FOR(i, a, b) for (int i=a; i<(b); i++) 14 | #define F0R(i, a) for (int i=0; i<(a); i++) 15 | #define FORd(i,a,b) for (int i = (b)-1; i >= a; i--) 16 | #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) 17 | 18 | #define sz(x) (int)(x).size() 19 | #define mp make_pair 20 | #define pb push_back 21 | #define f first 22 | #define s second 23 | #define lb lower_bound 24 | #define ub upper_bound 25 | 26 | const int MOD = 1000000007; 27 | const double PI = 4*atan(1); 28 | 29 | int a,b; 30 | 31 | void solve() { 32 | cin >> a >> b; 33 | cout << a*b << "\n"; 34 | } 35 | 36 | int main() { 37 | ios_base::sync_with_stdio(0);cin.tie(0); 38 | int n; cin >> n; 39 | FOR(i,1,n+1) { 40 | solve(); 41 | } 42 | } 43 | 44 | // read!read!read!read!read!read!read!read!read!read!read!read!read!read!read!read! 45 | // ll vs. int! 46 | -------------------------------------------------------------------------------- /Contests/Other Solutions/VT HSPC/2017/Difficulty Order.md: -------------------------------------------------------------------------------- 1 | Difficulty Order 2 | -------------- 3 | https://vthscontest.cs.cloud.vt.edu/contests/2/scoreboard 4 | 5 | ----- 6 | Misc Implementation 7 | C - 66 8 | K - 65 9 | F - 53 10 | A - 47 11 | H - 27 12 | ----- 13 | BFS 14 | E - 20 15 | ----- 16 | Binary Search 17 | J - 18 18 | ----- 19 | Math 20 | B - 14 21 | ----- 22 | Flows 23 | G - 4 24 | ----- 25 | Geometry 26 | L - 4 27 | ----- 28 | Brute Force 29 | D - 1 30 | ----- 31 | FFT 32 | I - 0 33 | -------------------------------------------------------------------------------- /Contests/Other Solutions/VT HSPC/2017/Weight.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | using namespace __gnu_pbds; 7 | 8 | typedef long long ll; 9 | typedef vector vi; 10 | typedef pair pii; 11 | template using Tree = tree, rb_tree_tag,tree_order_statistics_node_update>; 12 | 13 | #define FOR(i, a, b) for (int i=a; i<(b); i++) 14 | #define F0R(i, a) for (int i=0; i<(a); i++) 15 | #define FORd(i,a,b) for (int i = (b)-1; i >= a; i--) 16 | #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) 17 | 18 | #define sz(x) (int)(x).size() 19 | #define mp make_pair 20 | #define pb push_back 21 | #define f first 22 | #define s second 23 | #define lb lower_bound 24 | #define ub upper_bound 25 | #define all(x) x.begin(), x.end() 26 | 27 | const int MOD = 1000000007; 28 | const int MX = 100000; 29 | 30 | int l,w, num[40]; 31 | 32 | int main() { 33 | ios_base::sync_with_stdio(0);cin.tie(0); 34 | cin >> l >> w; 35 | if (w < l || w > 26*l) { 36 | cout << "impossible"; 37 | return 0; 38 | } 39 | F0R(i,w) num[i%l] ++; 40 | F0R(i,l) cout << char((num[i]-1)+'a'); 41 | } 42 | 43 | // read!read!read!read!read!read!read!read!read!read!read!read!read!read!read!read! 44 | // ll vs. int! -------------------------------------------------------------------------------- /Contests/Tools/Other/checker.py: -------------------------------------------------------------------------------- 1 | # use with grader 2 | 3 | import sys 4 | from grader import splitWhite 5 | 6 | inputF = sys.argv[1] 7 | outputF = sys.argv[2] 8 | o = sys.argv[3] 9 | 10 | verdict = 1 11 | 12 | def fassert(b): 13 | if not b: 14 | sys.exit(verdict) 15 | 16 | x = splitWhite(outputF) 17 | y = splitWhite(o) 18 | 19 | fassert(len(x) == len(y)) 20 | correct = 0 21 | 22 | for i in range(len(x)): 23 | fassert(len(x[i]) == len(y[i])) 24 | if len(x[i]) == 3: 25 | fassert(int(x[i][0])*int(x[i][1])*int(x[i][2]) == int(y[i][0])*int(y[i][1])*int(y[i][2])) 26 | fassert(y[i][0] != y[i][1] and y[i][0] != y[i][2] and y[i][1] != y[i][2]) 27 | else: 28 | fassert(x[i] == y[i]) 29 | correct += 1 30 | verdict = correct -------------------------------------------------------------------------------- /Contests/Tools/Other/ioi_probs.py: -------------------------------------------------------------------------------- 1 | from contextlib import closing 2 | from bs4 import BeautifulSoup 3 | import urllib.request 4 | import time 5 | import sys 6 | import os 7 | 8 | def parse(url): 9 | page = urllib.request.urlopen(url) 10 | return BeautifulSoup(page,'html.parser') 11 | 12 | def ioi_names(): 13 | for i in range(2003,2020): 14 | url = f"https://ioinformatics.org/page/ioi-{i}/{29-2003+i}" 15 | print("YEAR",i) 16 | html = parse(url) 17 | cool = html.find_all('a') 18 | co = 0 19 | for t in cool: 20 | if 'href' in t.attrs: 21 | tmp = t.attrs['href'] 22 | if "/files/" in tmp and "problem" in tmp: 23 | name = ''.join(t.find_all(text=True)) 24 | co += 1 25 | print(str(co)+" "+name) 26 | # sys.exit(0) 27 | 28 | def ioi_stats(): # parses stat table 29 | url = "https://stats.ioinformatics.org/tasks/" 30 | html = parse(url) 31 | for a in html.find_all('tr'): 32 | arr = [] 33 | for b in a.find_all('td'): 34 | arr.append(b.text) 35 | if len(arr) > 0 and len(arr[0]) == 4: 36 | if int(arr[0]) < 1994: 37 | break; 38 | print(arr[0]) 39 | arr.pop(0) 40 | if len(arr) > 0 and len(arr[0]) == 1 and len(arr[1]) == 1: 41 | arr.pop(0) 42 | if len(arr) > 0: 43 | print(arr) -------------------------------------------------------------------------------- /Contests/USACO Links/README.md: -------------------------------------------------------------------------------- 1 | # README 2 | 3 | Please let me know if anything is incorrectly categorized or if you have a better categorization system. 4 | 5 | ## Approximate CF Rating to USACO 6 | 7 | Assumes that you have done enough contests such that your rating has stabilized. 8 | 9 | * 1200+: Silver 10 | * 1400+: Gold 11 | * 1600+: Platinum 12 | * Personally I was ~1500 when making platinum (lol), but it's harder nowadays. 13 | * 1900+: Training Camp - Guernsey 14 | * 1900 is slightly above the mean rating of 2019 guernseys around April 2019 (whose profiles I could find). 15 | * However, the converse doesn't hold, meaning that a fair amount of people reach 1900 but never make camp. This is probably due to the fact that 12th graders can't qualify, and there might be a preference for 10th graders over 11th graders (?). 16 | * Training Camp - Holstein 17 | * Idk, too much variation. 18 | 19 | Please let me know if these are ~~outdated~~ blatantly wrong. -------------------------------------------------------------------------------- /Contests/USACO Solutions/2011-12/Mar/12 Mar G2.cpp: -------------------------------------------------------------------------------- 1 | /*#include 2 | #include */ 3 | #include 4 | 5 | using namespace std; 6 | //using namespace __gnu_pbds; 7 | 8 | typedef long long ll; 9 | typedef vector vi; 10 | typedef pair pi; 11 | //typedef tree,rb_tree_tag,tree_order_statistics_node_update> ordered_set; 12 | 13 | #define FOR(i, a, b) for (int i=a; i= a; i--) 16 | #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) 17 | 18 | #define mp make_pair 19 | #define pb push_back 20 | #define f first 21 | #define s second 22 | #define lb lower_bound 23 | #define ub upper_bound 24 | 25 | const int MOD = 1000000007; 26 | double PI = 4*atan(1); 27 | 28 | int n,c = 0; 29 | ll ans = 0; 30 | vi x; 31 | 32 | int main() { 33 | ios_base::sync_with_stdio(0);cin.tie(0); 34 | cin >> n; 35 | F0R(i,n) { 36 | int a,b; cin >> a >> b; 37 | c += (a-b); 38 | x.pb(c); 39 | } 40 | sort(x.begin(),x.end()); 41 | F0R(i,x.size()) ans += abs(x[i]-x[x.size()/2]); 42 | cout << ans; 43 | } 44 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2011-12/Mar/12 Mar S3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | typedef long long ll; 8 | typedef pair pi; 9 | typedef vector vi; 10 | 11 | #define mp make_pair 12 | #define pb push_back 13 | 14 | #define FOR(i, a, b) for (int i=a; i> N >> X >> Y >> Z; 29 | F0R(i,N) { 30 | int Ai, Bi; cin >> Ai >> Bi; 31 | F0R(j,Ai) A.pb(i); 32 | F0R(j,Bi) B.pb(i); 33 | } 34 | F0R(i,A.size()+1) dp[i][0] = i*Y; 35 | F0R(i,B.size()+1) dp[0][i] = i*X; 36 | FOR(i,1,A.size()+1) FOR(j,1,B.size()+1) { 37 | dp[i][j] = min(dp[i][j-1]+X,dp[i-1][j]+Y); 38 | dp[i][j] = min(dp[i][j],dp[i-1][j-1]+Z*abs(A[i-1]-B[j-1])); 39 | } 40 | cout << dp[A.size()][B.size()]; 41 | } 42 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Dec 2015/Bronze/15 Dec B1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | ofstream fout ("paint.out"); 9 | ifstream fin ("paint.in"); 10 | 11 | int array1[101]; 12 | 13 | int main() { 14 | int a, b, c, d; 15 | fin >> a >> b >> c >> d; 16 | for (int i = a; i < b; ++i) array1[i] = 1; 17 | for (int i = c; i < d; ++i) array1[i] = 1; 18 | int count = 0; 19 | for (int i = 0; i < 100; ++i) { 20 | if (array1[i] == 1) count++; 21 | } 22 | fout << count; 23 | } 24 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Dec 2015/Bronze/15 Dec B2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | ofstream fout ("speeding.out"); 9 | ifstream fin ("speeding.in"); 10 | 11 | int array1[100]; 12 | 13 | int main() { 14 | int M, N, count1 = 0, max1 = 0; 15 | fin >> N >> M; 16 | for (int i = 0; i < N; ++i) { 17 | int a,b; 18 | fin >> a >> b; 19 | for (int j = count1; j < a+count1; ++j) { 20 | array1[j] = b; 21 | } 22 | count1 = count1+a; 23 | } 24 | count1 = 0; 25 | for (int i = 0; i < M; ++i) { 26 | int a,b; 27 | fin >> a >> b; 28 | for (int j = count1; j < a+count1; ++j) { 29 | array1[j] = b-array1[j]; 30 | if(array1[j] > max1) max1 = array1[j]; 31 | } 32 | count1 = count1+a; 33 | } 34 | fout << max1; 35 | } 36 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Dec 2015/Gold/15 Dec G2.cpp: -------------------------------------------------------------------------------- 1 | // #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | ifstream cin ("feast.in"); 12 | ofstream cout ("feast.out"); 13 | 14 | int array1[5000001]; 15 | 16 | int findmax(int x) { 17 | for (int i = x; i >= 0; --i) { 18 | if (array1[i]) { 19 | return i; 20 | } 21 | } 22 | return 0; 23 | } 24 | 25 | int main() { 26 | int T,A,B, ans=0; 27 | cin >> T >> A >> B; 28 | array1[0] = 1; 29 | for (int i = 1; i <= T; ++i) { 30 | if (i-A>=0 && array1[i-A] == 1) { 31 | array1[i] = 1; 32 | } 33 | if (i-B>=0 && array1[i-B] == 1) { 34 | array1[i] = 1; 35 | } 36 | } 37 | 38 | for (int i = 0; i <= T; ++i) { 39 | if (array1[i]) { 40 | int j = i/2; 41 | int max = j+findmax(T-j); 42 | if (max > ans) ans = max; 43 | } 44 | } 45 | cout << ans; 46 | } 47 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Dec 2015/Silver/15 Dec S2.cpp: -------------------------------------------------------------------------------- 1 | // #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | ifstream cin ("highcard.in"); 12 | ofstream cout ("highcard.out"); 13 | 14 | int array1[100001]; 15 | vector v1,v2; 16 | 17 | int main () { 18 | int N; 19 | cin >> N; 20 | for (int i = 0; i < N; ++i) { 21 | int a; 22 | cin >> a; 23 | array1[a] = 1; 24 | } 25 | 26 | for (int i = 1; i <= 2*N; ++i) { 27 | if (array1[i] == 0) v1.push_back(i); 28 | if (array1[i] == 1) v2.push_back(i); 29 | } 30 | 31 | sort(v1.begin(),v1.end()); 32 | sort(v2.begin(),v2.end()); 33 | for (int i = N; i > 0; --i) { 34 | bool x = true; 35 | for (int j = i-1; j >= 0; --j) { 36 | if (v1[j] < v2[j]) { 37 | x = false; 38 | break; 39 | } 40 | } 41 | if (x == true) { 42 | cout << i; 43 | return 0; 44 | } 45 | v1.erase(v1.begin()); 46 | } 47 | cout << 0; 48 | } 49 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Dec 2015/Silver/15 Dec S3.cpp: -------------------------------------------------------------------------------- 1 | // #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | ifstream cin ("bcount.in"); 12 | ofstream cout ("bcount.out"); 13 | 14 | int array1[100001][4]; 15 | 16 | int main () { 17 | int N, Q; 18 | cin >> N >> Q; 19 | for (int i = 1; i <= N; ++i) { 20 | array1[i][1] = array1[i-1][1]; 21 | array1[i][2] = array1[i-1][2]; 22 | array1[i][3] = array1[i-1][3]; 23 | int a; 24 | cin >> a; 25 | array1[i][a]++; 26 | } 27 | for (int i = 0; i < Q; ++i) { 28 | int a,b; 29 | cin >> a >> b; 30 | cout << array1[b][1]-array1[a-1][1] << " " << array1[b][2]-array1[a-1][2] << " " << array1[b][3]-array1[a-1][3] << endl; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Feb 2016/Bronze/16 Feb B1.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | typedef vector vi; 9 | typedef pair pi; 10 | 11 | #define FOR(i, a, b) for (int i=a; i> X >> Y >> M; 22 | F0R(i,M/X+1) posi[i*X] = 1; 23 | F0R(j,M/Y+1) F0R(i,M) if (posi[i] && i+j*Y <= M) posi[i+j*Y] = 1; 24 | for (int i = M; i >= 0; --i) if (posi[i]) { 25 | cout << i; 26 | return 0; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Feb 2016/Bronze/16 Feb B2.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | typedef vector vi; 9 | typedef pair pi; 10 | 11 | #define FOR(i, a, b) for (int i=a; i> n; 21 | vi r(n); F0R(i,n) cin >> r[i]; 22 | F0R(i,n) { 23 | int ans = 0; 24 | F0R(j,n) ans += j*r[j]; 25 | r.pb(r[0]); 26 | r.erase(r.begin()); 27 | f = min(f,ans); 28 | } 29 | cout << f; 30 | } 31 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Feb 2016/Bronze/16 Feb B3.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | typedef vector vi; 10 | typedef pair pi; 11 | 12 | #define FOR(i, a, b) for (int i=a; i cow; 20 | 21 | void test(int x, int y) { 22 | int n1=0,n2=0,n3=0,n4=0; 23 | F0R(i,N) if (cow[i].f>x) { 24 | if (cow[i].s>y) { 25 | n1++; 26 | } else { 27 | n2++; 28 | } 29 | } else { 30 | if (cow[i].s>y) { 31 | n3++; 32 | } else { 33 | n4++; 34 | } 35 | } 36 | //cout << n1 << " " << n2 << " " << n3 << " " << n4 << "\n"; 37 | ans = min(ans,max(max(n1,n2),max(n3,n4))); 38 | } 39 | 40 | int main() { 41 | ifstream cin ("balancing.in"); 42 | ofstream cout ("balancing.out"); 43 | cin >> N >> B; cow.resize(N); 44 | F0R(i,N) cin >> cow[i].f >> cow[i].s; 45 | F0R(i,N) F0R(j,N) { 46 | test(cow[i].f+1,cow[j].s+1); 47 | } 48 | cout << ans; 49 | } 50 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Feb 2016/Gold/16 Feb G1.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | typedef long long ll; 8 | typedef vector vi; 9 | typedef pair pi; 10 | 11 | #define FOR(i, a, b) for (int i=a; i> n; 22 | int dif = 0; 23 | F0R(i,n) { 24 | b.pb(i); 25 | int t; cin >> t; 26 | F0R(j,t) a.pb(i); 27 | } 28 | F0R(i,n) dif = max(dif,a[i]-b[i]); 29 | F0R(i,n) b[i] += dif; 30 | ll ans = 0; 31 | F0R(i,n) ans += (a[i]-b[i])*(a[i]-b[i]); 32 | cout << ans; 33 | } 34 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Jan 2016/Bronze/16 Jan B1.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | typedef vector vi; 9 | typedef pair pi; 10 | 11 | #define FOR(i, a, b) for (int i=a; i> a.f >> a.s >> b.f >> b.s >> c.f >> c.s >> d.f >> d.s; 21 | int a1,a2,a3; 22 | a3 = d.s-d.f; 23 | c.s += a3; 24 | a2 = c.s-c.f; 25 | b.s += a2; 26 | a1 = b.s-b.f; 27 | cout << a1 << "\n" << a2 << "\n" << a3; 28 | } 29 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Jan 2016/Bronze/16 Jan B2.cpp: -------------------------------------------------------------------------------- 1 | // #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | typedef vector vi; 8 | typedef pair pi; 9 | 10 | #define FOR(i, a, b) for (int i=a; i0 && x[d1]-x[d-1] <= rad) d--; 30 | if (d == d1) break; 31 | rad++; 32 | } 33 | ans = max(ans,c-d+1); 34 | } 35 | 36 | int main() { 37 | ifstream cin ("angry.in"); 38 | ofstream cout ("angry.out"); 39 | cin >> N; x.resize(N); 40 | F0R(i,N) cin >> x[i]; 41 | sort(x.begin(),x.end()); 42 | F0R(i,N) test(i); 43 | cout << ans; 44 | } 45 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Jan 2016/Plat/16 Jan P1.cpp: -------------------------------------------------------------------------------- 1 | // #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | #define FOR(i, a, b) for (int i=a; i> N >> M; 25 | 26 | F0R(i,N) F0R(j,M) { 27 | char x; 28 | cin >> x; 29 | if (x == '.') grid[j][i] = 1; 30 | } 31 | 32 | F0R(i,M) F0R(j,N) { 33 | ok1[i][i][j] = grid[i][j]; 34 | FOR(i1,i+1,M) ok1[i][i1][j] = ok1[i][i1-1][j] & grid[i1][j]; 35 | } 36 | F0R(j,N) F0R(i,M) { 37 | ok2[j][j][i] = grid[i][j]; 38 | FOR(j1,j+1,N) ok2[j][j1][i] = ok2[j][j1-1][i] & grid[i][j1]; 39 | } 40 | F0R(a,M) FOR(b,a,M) F0R(c,N) FOR(d,c,N) { 41 | if ((b-a+1)*(d-c+1)>ans && test(a,b,c,d)) ans = (b-a+1)*(d-c+1); 42 | } 43 | 44 | cout << ans; 45 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Jan 2016/Silver/16 Jan S1.cpp: -------------------------------------------------------------------------------- 1 | // #include 2 | #include 3 | #include 4 | #include 5 | 6 | #define ll long long 7 | #define mp make_pair 8 | #define pb push_back 9 | #define pi pair 10 | #define vi vector 11 | 12 | #define FOR(i, a, b) for (int i=a; i> N >> K; 30 | F0R(i,N) { 31 | int n; 32 | cin >> n, nums.pb(n); 33 | } 34 | sort(nums.begin(), nums.end()); 35 | 36 | for (int R = 0; ; ++R) { 37 | int count = 0, index = 0; 38 | while (count < K && index < N) { 39 | int temp = nums[index]+2*R; 40 | while (nums[index] <= temp && index < N) index++; 41 | count++; 42 | } 43 | if (index == N) { 44 | cout << R; 45 | return 0; 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Jan 2016/Silver/16 Jan S2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | // ifstream cin ("div7.in"); 9 | // ofstream cout ("div7.out"); 10 | 11 | int N, pre[50001], ans=0; 12 | 13 | int main() { 14 | cin >> N; 15 | for (int i = 1; i <= N; ++i) { 16 | cin >> pre[i]; 17 | pre[i] += pre[i-1]; 18 | pre[i] %= 7; 19 | } 20 | for (int r = 0; r < 7; ++r) { 21 | int a=N,b=0; 22 | for (int i = 0; i <= N; ++i) { 23 | if (pre[i] == r) { 24 | a = i; 25 | break; 26 | } 27 | } 28 | for (int i = N; i >= 0; --i) { 29 | if (pre[i] == r) { 30 | b = i; 31 | break; 32 | } 33 | } 34 | if (b-a>ans)ans=b-a; 35 | } 36 | cout << ans; 37 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Open 2016/Bronze/16 Open B1.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | typedef vector vi; 10 | typedef pair pi; 11 | 12 | #define FOR(i, a, b) for (int i=a; i> N >> K; 22 | vi x(N); F0R(i,N) cin >> x[i]; 23 | sort(x.begin(),x.end()); 24 | F0R(i,N) { 25 | FOR(j,i,N) { 26 | if (x[j]-x[i] <= K) ans = max(ans,j-i+1); 27 | else break; 28 | } 29 | } 30 | cout << ans; 31 | } 32 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2015-16/Open 2016/Gold/16 Open G3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | #define ll long long 7 | #define mp make_pair 8 | #define pb push_back 9 | #define pi pair 10 | #define vi vector 11 | 12 | #define FOR(i, a, b) for (int i=a; i=b; i--) 14 | #define F0Rd(i, a) for (int i=a-1; i>=0; i--) 15 | #define F0R(i, a) for (int i=0; i sequence[60]; 29 | cin >> n; 30 | F0R(i,n) { 31 | int x; cin >> x; 32 | sequence[x].pb(mp(i,i+1)); 33 | } 34 | 35 | FOR(i,1,59) { 36 | int it = 0; 37 | if (sequence[i].size()) ans = i; 38 | sort(sequence[i].b(),sequence[i].e()); 39 | F0R(j,sequence[i].size()) { 40 | while (sequence[i][it].f < sequence[i][j].s && it 2 | 3 | using namespace std; 4 | 5 | typedef pair pi; 6 | 7 | #define f first 8 | #define s second 9 | 10 | int main() { 11 | // freopen("square.in","r",stdin); 12 | // freopen("square.out","w",stdout); 13 | 14 | pi a,b,c,d; cin >> a.f >> a.s >> b.f >> b.s >> c.f >> c.s >> d.f >> d.s; 15 | int ans = max(max(a.f,b.f),max(c.f,d.f))-min(min(a.f,b.f),min(c.f,d.f)); 16 | ans = max(ans,max(max(a.s,b.s),max(c.s,d.s))-min(min(a.s,b.s),min(c.s,d.s))); 17 | cout << ans*ans; 18 | } 19 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Dec 2016/Bronze/16 Dec B2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // #include 4 | 5 | using namespace std; 6 | 7 | typedef long long ll; 8 | typedef pair pi; 9 | typedef vector vi; 10 | 11 | #define mp make_pair 12 | #define pb push_back 13 | 14 | #define FOR(i, a, b) for (int i=a; i> N; 29 | vi a(26); 30 | F0R(i,N) { 31 | vi b(26),c(26); 32 | string b1, c1; cin >> b1 >> c1; 33 | for (char j: b1) b[int(j-'a')]++; 34 | for (char j: c1) c[int(j-'a')]++; 35 | F0R(j,26) a[j] += max(b[j],c[j]); 36 | } 37 | F0R(i,26) cout << a[i] << "\n"; 38 | } 39 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Dec 2016/Bronze/16 Dec B3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | #define F0R(i, a) for (int i=0; i> M >> N >> K; 14 | F0R(i,M) F0R(j,N) cin >> ori[i][j]; 15 | F0R(i,K*M) { 16 | F0R(j,K*N) cout << ori[i/K][j/K]; 17 | cout << "\n"; 18 | } 19 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Dec 2016/Silver/16 Dec S2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | #define F0R(i, a) for (int i=0; i,int> times; 13 | 14 | int main() { 15 | // ifstream cin ("citystate.in"); 16 | // ofstream cout ("citystate.out"); 17 | int N; cin >> N; 18 | F0R(i,N) { 19 | string a,b; cin >> a >> b; 20 | a = a.substr(0,2); 21 | if (a != b) times[{a,b}]++; 22 | } 23 | long long ans = 0; 24 | for (auto a: times) ans += a.s*times[{a.f.s,a.f.f}]; 25 | cout << ans/2; 26 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Feb 2017/Bronze/17 Feb B1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | #define FOR(i, a, b) for (int i=a; i> n; 15 | F0R(i,n) { 16 | int a,b; cin >> a >> b; 17 | if (cur[a] != -1 && cur[a] != b) ans++; 18 | cur[a] = b; 19 | } 20 | cout << ans; 21 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Feb 2017/Bronze/17 Feb B2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | //using namespace __gnu_pbds; 5 | 6 | typedef long long ll; 7 | typedef vector vi; 8 | typedef pair pi; 9 | //typedef tree,rb_tree_tag,tree_order_statistics_node_update> ordered_set; 10 | 11 | #define FOR(i, a, b) for (int i=a; i= a; i--) 14 | #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) 15 | 16 | #define mp make_pair 17 | #define pb push_back 18 | #define f first 19 | #define s second 20 | #define lb lower_bound 21 | #define ub upper_bound 22 | 23 | const int MOD = 1000000007; 24 | double PI = 4*atan(1); 25 | 26 | vi pairs[26]; 27 | 28 | int main() { 29 | string x; cin >> x; 30 | F0R(i,x.length()) pairs[x[i]-'A'].pb(i); 31 | int ans = 0; 32 | F0R(i,26) F0R(j,26) 33 | if (i != j) 34 | if (pairs[i][0] pairs[j][0] && pairs[j][1] > pairs[i][1]) 35 | ans++; 36 | 37 | cout << ans; 38 | } 39 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Feb 2017/Bronze/17 Feb B3.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | typedef pair pi; 6 | 7 | #define FOR(i, a, b) for (int i=a; i> n; 15 | vector cow(n); 16 | F0R(i,n) cin >> cow[i].f >> cow[i].s; 17 | sort(cow.begin(),cow.end()); 18 | F0R(i,n) { 19 | int cur = cow[i].f; 20 | FOR(j,i,n) cur += cow[j].s; 21 | ans = max(ans,cur); 22 | } 23 | cout << ans; 24 | } 25 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Feb 2017/Gold/17 Feb G3.cpp: -------------------------------------------------------------------------------- 1 | //#include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | using namespace __gnu_pbds; 10 | 11 | #define F0R(i, a) for (int i=0; i ID[50001]; 17 | int nums[100000]; 18 | tree,rb_tree_tag,tree_order_statistics_node_update> cur; 19 | long long ans = 0; 20 | 21 | int main() { 22 | ifstream cin ("circlecross.in"); 23 | ofstream cout ("circlecross.out"); 24 | int N; cin >> N; 25 | F0R(i,50001) ID[i] = {-1,-1}; 26 | F0R(i,2*N) { 27 | int k; cin >> k; nums[i] = k; 28 | if (ID[k].f != -1) ID[k].s = i; 29 | else ID[k].f = i; 30 | } 31 | F0R(i,2*N) { 32 | if (i == ID[nums[i]].f) { 33 | ans += cur.order_of_key(ID[nums[i]].s); 34 | cur.insert(ID[nums[i]].s); 35 | } else cur.erase(ID[nums[i]].s); 36 | } 37 | cout << ans; 38 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Feb 2017/Plat/17 Feb P1 (Set).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace __gnu_pbds; 7 | using namespace std; 8 | 9 | typedef long long ll; 10 | 11 | #define F0R(i, a) for (int i=0; i,rb_tree_tag,tree_order_statistics_node_update> s; 19 | ll cur = N*(N-1)/2; 20 | F0R(i,N) { 21 | b[i] = m[y[i]]; 22 | cur -= s.order_of_key(b[i]); 23 | s.insert(b[i]); 24 | } 25 | for (int i = N-1; i >= 0; --i) { 26 | ans = min(ans,cur); 27 | cur += (2*b[i]+1-N); 28 | } 29 | } 30 | 31 | int main() { 32 | // ifstream cin ("mincross.in"); 33 | // ofstream cout ("mincross.out"); 34 | cin >> N; 35 | F0R(i,N) cin >> x[i]; 36 | F0R(i,N) cin >> y[i]; 37 | solve(), swap(x,y), solve(); 38 | cout << ans; 39 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Feb 2017/Silver/17 Feb S1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | typedef vector vi; 10 | typedef pair pi; 11 | 12 | #define F0R(i, a) for (int i=0; i> C >> N; 21 | vi c(C); 22 | vector n(N); 23 | F0R(i,C) cin >> c[i]; 24 | F0R(i,N) cin >> n[i].f >> n[i].s; 25 | sort(c.begin(),c.end()); 26 | sort(n.begin(),n.end()); 27 | multiset cur; 28 | int ind = -1, ans = 0; 29 | for (int i: c) { 30 | while (ind<(int)n.size()-1 && n[ind+1].f <= i) cur.insert(n[++ind].s); 31 | while (cur.size() && (*cur.begin()) 2 | #include 3 | 4 | using namespace std; 5 | 6 | #define FOR(i, a, b) for (int i=a; i> N >> K >> B; 15 | F0R(i,B) { 16 | int b; cin >> b; 17 | bad[b] = 1; 18 | } 19 | int low = 1, high = K, cur = 0, ans = 1000000007; 20 | FOR(i,low,high+1) cur += bad[i]; 21 | while (1) { 22 | ans = min(ans,cur); 23 | if (high == N) break; 24 | cur += (bad[++high] - bad[low++]); 25 | } 26 | cout << ans; 27 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Jan 2017/Plat/17 Jan P2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | // #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | typedef long long ll; 9 | typedef long double ld; 10 | typedef vector vi; 11 | 12 | #define FOR(i, a, b) for (int i=a; i a; 19 | ld low = 0, high = 1e12+1; 20 | 21 | int main() { 22 | ll N,K; cin >> N >> K; 23 | a.resize(N); 24 | F0R(i,N) cin >> a[i]; 25 | int z = 0; 26 | while (high-low>0.00000001) { 27 | ld mid = (low+high)/2; 28 | z++; 29 | // cout << high-low << "\n"; 30 | ll count = 0; 31 | for (ll A: a) { 32 | count += ceil((-1+sqrt(1+4*A/mid))/2); 33 | if (count>K) break; 34 | } 35 | if (count <= K) high = mid; 36 | else low = mid; 37 | } 38 | ll count = 0; 39 | ld ans = 0; 40 | for (ll A: a) { 41 | ll t = ceil((-1+sqrt(1+4*(ld)A/high))/2); 42 | ans += (ld)A/t; 43 | count += t; 44 | } 45 | ans -= (K-count)*high; 46 | ll k = round(ans); 47 | cout << k; 48 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Jan 2017/Plat/promo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | using namespace __gnu_pbds; 7 | 8 | template using Tree = tree,rb_tree_tag,tree_order_statistics_node_update>; 9 | 10 | const int MX = 1e5+5; 11 | #define sz(x) (int)(x).size() 12 | 13 | int N, a[MX], ind[MX], ans[MX], ret; 14 | vector child[MX]; 15 | Tree d[MX]; 16 | 17 | void comb(int a, int b) { 18 | if (sz(d[a]) < sz(d[b])) d[a].swap(d[b]); 19 | for (int i: d[b]) d[a].insert(i); 20 | } 21 | 22 | void dfs(int x) { 23 | ind[x] = x; 24 | for (int i: child[x]) { 25 | dfs(i); 26 | comb(x,i); 27 | } 28 | ans[x] = sz(d[x])-d[x].order_of_key(a[x]); 29 | d[x].insert(a[x]); 30 | } 31 | 32 | int main() { 33 | freopen("promote.in","r",stdin); 34 | freopen("promote.out","w",stdout); 35 | cin >> N; for (int i = 1; i <= N; ++i) cin >> a[i]; 36 | for (int i = 2; i <= N; ++i) { 37 | int p; cin >> p; 38 | child[p].push_back(i); 39 | } 40 | dfs(1); 41 | for (int i = 1; i <= N; ++i) cout << ans[i] << "\n"; 42 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Open 2017/Bronze/17 Open B1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | //using namespace __gnu_pbds; 6 | 7 | typedef long long ll; 8 | typedef vector vi; 9 | typedef pair pi; 10 | //typedef tree,rb_tree_tag,tree_order_statistics_node_update> ordered_set; 11 | 12 | #define FOR(i, a, b) for (int i=a; i= a; i--) 15 | #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) 16 | 17 | #define mp make_pair 18 | #define pb push_back 19 | #define f first 20 | #define s second 21 | #define lb lower_bound 22 | #define ub upper_bound 23 | 24 | ifstream cin ("lostcow.in"); 25 | ofstream cout ("lostcow.out"); 26 | 27 | int dist = 1; 28 | 29 | int main() { 30 | int x,y; cin >> x >> y; 31 | int x1 = x+1; 32 | while (1) { 33 | int x2 = 2*(x-x1)+x; 34 | if (min(x1,x2) <= y && y <= max(x1,x2)) { 35 | dist += abs(x1-y); 36 | break; 37 | } else dist += 3*abs(x-x1); 38 | x1 = x2; 39 | } 40 | cout << dist; 41 | } 42 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2016-17/Open 2017/Bronze/17 Open B2.cpp: -------------------------------------------------------------------------------- 1 | // #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | //using namespace __gnu_pbds; 8 | 9 | typedef long long ll; 10 | typedef vector vi; 11 | typedef pair pi; 12 | //typedef tree,rb_tree_tag,tree_order_statistics_node_update> ordered_set; 13 | 14 | #define FOR(i, a, b) for (int i=a; i= a; i--) 17 | #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) 18 | 19 | #define mp make_pair 20 | #define pb push_back 21 | #define f first 22 | #define s second 23 | #define lb lower_bound 24 | #define ub upper_bound 25 | 26 | ifstream cin("cownomics.in"); 27 | ofstream cout ("cownomics.out"); 28 | 29 | int n,m,ans; 30 | map x; 31 | vector v1, v2; 32 | 33 | int main() { 34 | cin >> n >> m; v1.resize(n), v2.resize(n); 35 | x['A'] = 0; 36 | x['C'] = 1; 37 | x['G'] = 2; 38 | x['T'] = 3; 39 | F0R(i,n) cin >> v1[i]; 40 | F0R(i,n) cin >> v2[i]; 41 | F0R(i,m) { 42 | int a=0,b=0; 43 | F0R(j,n) a |= (1< 2 | 3 | using namespace std; 4 | 5 | 6 | //answer is the (maximum number of neighbors a vertex has) + 1 7 | 8 | int main(){ 9 | ios::sync_with_stdio(false); 10 | cin.tie(0); 11 | 12 | ifstream fin ("planting.in"); 13 | ofstream fout ("planting.out"); 14 | 15 | int n; 16 | fin >> n; 17 | 18 | vector> adj(n+1); 19 | 20 | for(int k = 0; k < n-1; k++){ 21 | int a,b; 22 | fin >> a >> b; 23 | 24 | adj[a].push_back(b); 25 | adj[b].push_back(a); 26 | } 27 | 28 | int answer = 0; 29 | for(int k = 1; k <= n; k++){ 30 | answer = max(answer,static_cast(adj[k].size())); 31 | } 32 | 33 | cout << answer+1; 34 | fout << answer+1; 35 | 36 | 37 | 38 | 39 | 40 | 41 | return 0; 42 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2018-19/Open 2019/Gold/walk (senpat).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | ifstream fin ("walk.in"); 6 | ofstream fout ("walk.out"); 7 | int n,k; fin >> n >> k; 8 | int answer = 2019201997 - 48*n - 84*(k-1); 9 | fout << answer << endl; 10 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2019-20/Dec/Silver/milkvisits.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef vector vi; 5 | 6 | #define FOR(i,a,b) for (int i = (a); i < (b); ++i) 7 | #define F0R(i,a) FOR(i,0,a) 8 | #define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i) 9 | #define R0F(i,a) ROF(i,0,a) 10 | #define trav(a,x) for (auto& a: x) 11 | 12 | #define pb push_back 13 | 14 | void setIO(string name) { 15 | ios_base::sync_with_stdio(0); cin.tie(0); 16 | freopen((name+".in").c_str(),"r",stdin); 17 | freopen((name+".out").c_str(),"w",stdout); 18 | } 19 | 20 | const int MX = 100005; 21 | 22 | int N,M,comp[MX],num; 23 | char col[MX]; 24 | vi adj[MX]; 25 | 26 | void dfs(int x) { 27 | if (comp[x]) return; 28 | comp[x] = num; 29 | trav(t,adj[x]) if (col[t] == col[x]) dfs(t); 30 | } 31 | 32 | int main() { 33 | setIO("milkvisits"); cin >> N >> M; 34 | string s; cin >> s; 35 | FOR(i,1,N+1) col[i] = s[i-1]; 36 | F0R(i,N-1) { 37 | int A,B; cin >> A >> B; 38 | adj[A].pb(B), adj[B].pb(A); 39 | } 40 | FOR(i,1,N+1) if (!comp[i]) { 41 | num ++; 42 | dfs(i); 43 | } 44 | F0R(i,M) { 45 | int A,B; char C; cin >> A >> B >> C; 46 | if (col[A] == C || comp[A] != comp[B]) cout << 1; 47 | else cout << 0; 48 | } 49 | cout << "\n"; 50 | } 51 | -------------------------------------------------------------------------------- /Contests/USACO Solutions/2019-20/Feb/Gold/help.cpp: -------------------------------------------------------------------------------- 1 | #include "bits/stdc++.h" 2 | 3 | using namespace std; 4 | 5 | void setIO(string s) { 6 | ios_base::sync_with_stdio(0); cin.tie(0); 7 | freopen((s+".in").c_str(),"r",stdin); 8 | freopen((s+".out").c_str(),"w",stdout); 9 | } 10 | 11 | #define f first 12 | #define s second 13 | 14 | const int MOD = 1e9+7; 15 | 16 | int N; 17 | 18 | int main() { 19 | setIO("help"); 20 | cin >> N; vector> v(N); 21 | for (auto& a: v) cin >> a.f >> a.s; 22 | vector over(2*N+1), po2(N); 23 | po2[0] = 1; for (int i = 1; i < N; ++i) po2[i] = 2*po2[i-1]%MOD; 24 | for (auto& t: v) over[t.f] ++, over[t.s] --; 25 | for (int i = 1; i <= 2*N; ++i) over[i] += over[i-1]; 26 | int ans = 0; for (auto& t: v) ans = (ans+po2[N-1-over[t.f-1]])%MOD; 27 | cout << ans << "\n"; 28 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2019-20/Feb/Gold/timeline.cpp: -------------------------------------------------------------------------------- 1 | #include "bits/stdc++.h" 2 | 3 | using namespace std; 4 | 5 | void setIO(string s) { 6 | ios_base::sync_with_stdio(0); cin.tie(0); 7 | freopen((s+".in").c_str(),"r",stdin); 8 | freopen((s+".out").c_str(),"w",stdout); 9 | } 10 | 11 | #define f first 12 | #define s second 13 | 14 | const int MX = 1e5+5; 15 | 16 | int N,M,C,S[MX],in[MX]; 17 | bool vis[MX]; 18 | vector> adj[MX]; 19 | queue q; 20 | 21 | int main() { 22 | setIO("timeline"); 23 | cin >> N >> M >> C; 24 | for (int i = 1; i <= N; ++i) cin >> S[i]; 25 | for (int i = 0; i < C; ++i) { 26 | int a,b,x; cin >> a >> b >> x; 27 | adj[a].push_back({b,x}); in[b] ++; 28 | } 29 | for (int i = 1; i <= N; ++i) if (!in[i]) q.push(i); 30 | while (q.size()) { 31 | int x = q.front(); q.pop(); 32 | vis[x] = 1; assert(S[x] <= M); 33 | for (auto& t: adj[x]) { 34 | S[t.f] = max(S[t.f],S[x]+t.s); 35 | if (!(--in[t.f])) q.push(t.f); 36 | } 37 | } 38 | for (int i = 1; i <= N; ++i) { 39 | assert(vis[i]); 40 | cout << S[i] << "\n"; 41 | } 42 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2019-20/Jan/Bronze/word_dhruv.py: -------------------------------------------------------------------------------- 1 | import sys 2 | with open("word.in","r") as fin: 3 | L = list(fin) 4 | N,W = map(int,L[0].split()) 5 | with open("word.out","w") as fout: 6 | w = 0 7 | for c in L[1].split(): 8 | if w+len(c) > W: 9 | fout.write("\n"+c) 10 | w = len(c) 11 | else: 12 | if w > 0: 13 | fout.write(" ") 14 | fout.write(c) 15 | w += len(c) 16 | fout.write("\n") -------------------------------------------------------------------------------- /Contests/USACO Solutions/2019-20/Jan/Gold/boards.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define f first 5 | #define s second 6 | 7 | void setIO(string name) { 8 | ios_base::sync_with_stdio(0); cin.tie(0); 9 | freopen((name+".in").c_str(),"r",stdin); 10 | freopen((name+".out").c_str(),"w",stdout); 11 | } 12 | 13 | const int MX = 1e5+5; 14 | 15 | int N,P; 16 | map m; 17 | int ans[MX]; 18 | 19 | void ins(int y, int v) { 20 | auto it = prev(m.upper_bound(y)); 21 | if (it->s <= v) return; 22 | it ++; 23 | while (it != end(m) && it->s > v) m.erase(it++); 24 | m[y] = v; 25 | } 26 | 27 | int main() { 28 | setIO("boards"); 29 | cin >> N >> P; m[0] = 0; 30 | vector,pair>> ev; 31 | for (int i = 0; i < P; ++i) { 32 | pair a,b; 33 | cin >> a.f >> a.s >> b.f >> b.s; 34 | ev.push_back({a,{i,-1}}); // start point 35 | ev.push_back({b,{i,1}}); // end point 36 | } 37 | sort(begin(ev),end(ev)); 38 | for (auto& t: ev) { 39 | if (t.s.s == -1) { 40 | ans[t.s.f] = t.f.f+t.f.s+prev(m.upper_bound(t.f.s))->s; 41 | } else { 42 | ins(t.f.s,ans[t.s.f]-t.f.f-t.f.s); 43 | } 44 | } 45 | cout << m.rbegin()->s+2*N; 46 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2019-20/Open/Gold/haircut.cpp: -------------------------------------------------------------------------------- 1 | #include "bits/stdc++.h" 2 | 3 | using namespace std; 4 | 5 | void setIO(string s) { 6 | ios_base::sync_with_stdio(0); cin.tie(0); 7 | freopen((s+".in").c_str(),"r",stdin); 8 | freopen((s+".out").c_str(),"w",stdout); 9 | } 10 | 11 | #include 12 | #include 13 | using namespace __gnu_pbds; 14 | template using Tree = tree, 15 | rb_tree_tag, tree_order_statistics_node_update>; 16 | 17 | const int MX = 1e5+5; 18 | 19 | int N; 20 | long long numInv[MX]; 21 | vector todo[MX]; 22 | 23 | int main() { 24 | setIO("haircut"); 25 | int N; cin >> N; 26 | vector A(N); for (int& t: A) cin >> t; 27 | for (int i = 0; i < N; ++i) todo[A[i]].push_back(i); 28 | Tree T; 29 | for (int i = N; i >= 0; --i) { 30 | for (int t: todo[i]) numInv[i+1] += T.order_of_key(t); 31 | for (int t: todo[i]) T.insert(t); 32 | } 33 | for (int i = 1; i < N; ++i) numInv[i] += numInv[i-1]; 34 | for (int i = 0; i < N; ++i) cout << numInv[i] << "\n"; 35 | } -------------------------------------------------------------------------------- /Contests/USACO Solutions/2020-21/Dec/Bronze/abc.py: -------------------------------------------------------------------------------- 1 | inp = list(sorted(map(int,input().split()))) 2 | a,b = inp[0],inp[1] 3 | c = inp[-1]-a-b 4 | print(a,b,c) -------------------------------------------------------------------------------- /Contests/USACO Training/Ch 1/1.1 ride.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ID: bqi3431 3 | PROG: ride 4 | LANG: C++11 5 | */ 6 | 7 | #include 8 | 9 | using namespace std; 10 | 11 | int main() { 12 | ifstream cin ("ride.in"); 13 | ofstream cout ("ride.out"); 14 | string a,b; cin >> a >> b; 15 | int n1=1,n2=1; 16 | for (char a1: a) n1 = (n1*(a1-'A'+1)) % 47; 17 | for (char b1: b) n2 = (n2*(b1-'A'+1)) % 47; 18 | if (n1 == n2) cout << "GO"; 19 | else cout << "STAY"; 20 | cout << "\n"; 21 | } -------------------------------------------------------------------------------- /Contests/USACO Training/Ch 2/2.1 frac1.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ID: bqi3431 3 | PROG: frac1 4 | LANG: C++11 5 | */ 6 | 7 | //#include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | 14 | using namespace std; 15 | using namespace __gnu_pbds; 16 | 17 | typedef long long ll; 18 | typedef vector vi; 19 | typedef pair pi; 20 | typedef tree,rb_tree_tag,tree_order_statistics_node_update> ordered_set; 21 | 22 | #define FOR(i, a, b) for (int i=a; i= a; i--) 25 | #define F0Rd(i,a) for (int i = (a)-1; i >= 0; i--) 26 | 27 | #define mp make_pair 28 | #define pb push_back 29 | #define f first 30 | #define s second 31 | #define lb lower_bound 32 | #define ub upper_bound 33 | 34 | const int MOD = 1000000007; 35 | double PI = 4*atan(1); 36 | 37 | ifstream cin ("frac1.in"); 38 | ofstream cout ("frac1.out"); 39 | 40 | bool comp(pi a, pi b) { 41 | return (a.f*b.s k; 45 | 46 | int main() { 47 | int N; cin >> N; 48 | F0R(i,N+1) FOR(j,i,N+1) if (__gcd(i,j) == 1) k.pb({i,j}); 49 | sort(k.begin(),k.end(),comp); 50 | for (auto a: k) cout << a.f << "/" << a.s << "\n"; 51 | } 52 | -------------------------------------------------------------------------------- /Contests/USACO Training/Ch 2/2.3 nocows.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ID: bqi3431 3 | PROB: nocows 4 | LANG: C++11 5 | */ 6 | 7 | #include 8 | using namespace std; 9 | #define FOR(i, a, b) for (int i=a; i> n >> h; 17 | FOR(i,1,201) FOR(j,1,201) { 18 | if (i == 1) dparr[i][j] = 1; 19 | FOR(k,1,i-1) dparr[i][j] = (dparr[i][j]+dparr[k][j-1]*dparr[i-1-k][j-1]) % 9901; 20 | } 21 | cout << (dparr[n][h]-dparr[n][h-1]+9901) % 9901 << "\n"; 22 | } -------------------------------------------------------------------------------- /Contests/USACO Training/Ch 2/2.3 prefix.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ID: bqi3431 3 | PROG: prefix 4 | LANG: C++11 5 | */ 6 | 7 | #include 8 | #include 9 | #include 10 | 11 | using namespace std; 12 | 13 | #define FOR(i, a, b) for (int i=a; i p; 21 | 22 | int main() { 23 | string s,s1; 24 | while (cin >> s1) { 25 | if (s1 == ".") break; 26 | p.pb(s1); 27 | } 28 | while (cin >> s1) s += s1; 29 | dp[0] = 1; 30 | FOR(i,1,s.length()+1) for (string k: p) if (k.length() <= i) 31 | if (dp[i-k.length()] && s.substr(i-k.length(),k.length()) == k) { 32 | dp[i] = 1; 33 | ans = i; 34 | break; 35 | } 36 | cout << ans << "\n"; 37 | } -------------------------------------------------------------------------------- /Contests/USACO Training/Ch 6/6.1 cowxor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ID: bqi3431 3 | LANG: C++11 4 | TASK: cowxor 5 | */ 6 | 7 | // #include 8 | #include 9 | #include 10 | 11 | using namespace std; 12 | 13 | #define F0R(i, a) for (int i=0; i> len); 24 | if (z[cur^q] == -1) z[q] = (i+1); 25 | else return se(cur,len-1); 26 | } 27 | return se(cur-1,len-1); 28 | } 29 | 30 | int main() { 31 | ifstream cin ("cowxor.in"); 32 | ofstream cout ("cowxor.out"); 33 | 34 | cin >> N; 35 | F0R(i,N) cin >> cow[i]; 36 | int k = se(0,20), q = 0; 37 | memset(z,-1,(1<<21)*sizeof(int)); 38 | z[0] = 0; 39 | F0R(i,N) { 40 | q ^= cow[i]; 41 | if (z[k^q] != -1) { 42 | cout << k << " " << (z[k^q]+1) << " " << (i+1) << endl; 43 | return 0; 44 | } else z[q] = (i+1); 45 | } 46 | } -------------------------------------------------------------------------------- /Contests/USACO Training/Ch 6/6.1 vans.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ID: bqi3431 3 | LANG: C++11 4 | PROG: vans 5 | */ 6 | 7 | #include 8 | #include 9 | 10 | #define FOR(i,a,b) for (int i = a; i < b; ++i) 11 | #define F0R(i,a) for (int i = 0; i < a; ++i) 12 | #define vi vector 13 | 14 | using namespace std; 15 | 16 | ifstream cin ("vans.in"); 17 | ofstream cout ("vans.out"); 18 | 19 | vi a[1001], b[1001], c[1001]; 20 | 21 | vi make() { 22 | vi k(500); 23 | return k; 24 | } 25 | 26 | vi sum(vi x, vi y) { 27 | vi z = make(); 28 | F0R(i,500) { 29 | z[i] += x[i]+y[i]; 30 | if (z[i] > 9) { 31 | z[i] -= 10; 32 | z[i+1] ++; 33 | } 34 | } 35 | return z; 36 | } 37 | 38 | void print(vi x) { 39 | bool f = 0; 40 | for (int i = 499; i >= 0; --i) { 41 | if (x[i] == 0) { 42 | if (f) cout << 0; 43 | } else { 44 | f = 1; 45 | cout << x[i]; 46 | } 47 | } 48 | if (f == 0) cout << 0; 49 | cout << endl; 50 | } 51 | 52 | int main() { 53 | F0R(i,3) { 54 | a[i] = make(); 55 | b[i] = make(); 56 | c[i] = make(); 57 | } 58 | b[2][0] = 2; 59 | FOR(i,3,1001) { 60 | a[i] = sum(sum(a[i-1],b[i-1]),c[i-1]); 61 | vi temp = sum(sum(a[i-2],b[i-2]),c[i-2]); 62 | b[i] = sum(sum(temp,temp),b[i-1]); 63 | c[i] = sum(b[i-2],c[i-2]); 64 | } 65 | int N; cin >> N; 66 | print(sum(sum(a[N],b[N]),c[N])); 67 | } -------------------------------------------------------------------------------- /Implementations/CP Guide Contents.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bqi343/cp-notebook/292c614b7b83c355b188234966b3b336bc009f16/Implementations/CP Guide Contents.pdf -------------------------------------------------------------------------------- /Implementations/content/combinatorial (11.2)/DeBruijnSeq.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Given alphabet $[0,k)$ constructs a cyclic string 3 | * of length $k^n$ that contains every length $n$ string as substr. 4 | * Source: https://github.com/koosaga/DeobureoMinkyuParty/blob/master/teamnote.tex 5 | * https://en.wikipedia.org/wiki/De_Bruijn_sequence 6 | * pg 241 of http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.93.5967&rep=rep1&type=pdf 7 | * Verification: https://codeforces.com/gym/102001/problem/C 8 | */ 9 | 10 | vi deBruijnSeq(int k, int n) { /// Recursive FKM 11 | if (k == 1) return {0}; 12 | vi seq, aux(n+1); 13 | function gen = [&](int t, int p) { 14 | if (t > n) { // +lyndon word of len p 15 | if (n%p == 0) FOR(i,1,p+1) seq.pb(aux[i]); 16 | } else { 17 | aux[t] = aux[t-p]; gen(t+1,p); 18 | while (++aux[t] < k) gen(t+1,t); 19 | } 20 | }; 21 | gen(1,1); return seq; 22 | } -------------------------------------------------------------------------------- /Implementations/content/combinatorial (11.2)/IntPerm.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Unused. Convert permutation of $\{0,1,...,N-1\}$ to integer in $[0,N!)$ and back. 3 | * Source: http://antoinecomeau.blogspot.com/2014/07/mapping-between-permutations-and.html 4 | * Verification: ? 5 | * Time: O(N) 6 | * Usage: assert(encode(decode(5,37)) == 37); 7 | */ 8 | 9 | vi decode(int n, int a) { 10 | vi el(n), b; iota(all(el),0); 11 | F0R(i,n) { 12 | int z = a%sz(el); 13 | b.pb(el[z]); a /= sz(el); 14 | swap(el[z],el.bk); el.pop_back(); 15 | } 16 | return b; 17 | } 18 | int encode(vi b) { 19 | int n = sz(b), a = 0, mul = 1; 20 | vi pos(n); iota(all(pos),0); vi el = pos; 21 | F0R(i,n) { 22 | int z = pos[b[i]]; a += mul*z; mul *= sz(el); 23 | swap(pos[el[z]],pos[el.bk]); 24 | swap(el[z],el.bk); el.pop_back(); 25 | } 26 | return a; 27 | } 28 | -------------------------------------------------------------------------------- /Implementations/content/combinatorial (11.2)/README.md: -------------------------------------------------------------------------------- 1 | # Combinatorial 2 | 3 | ### 5 4 | 5 | * Combinatorics 6 | * Tutorial 7 | * CPH (22, Combinatorics) 8 | * [TopCoder](https://www.topcoder.com/community/data-science/data-science-tutorials/basics-of-combinatorics/) 9 | * Problems 10 | * [Obsession](http://codeforces.com/contest/869/problem/C) [](79) 11 | * [Barrels & Boxes](http://codeforces.com/contest/768/problem/F) [](83) 12 | * [String Mark](http://codeforces.com/contest/895/problem/D) [](108) -------------------------------------------------------------------------------- /Implementations/content/combinatorial (11.2)/factorial.tex: -------------------------------------------------------------------------------- 1 | \begin{center} 2 | \begin{tabular}{l} 3 | \begin{tabular}{c|c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c} 4 | $n$ & 1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 & 9 & 10\\ 5 | \hline 6 | $n!$ & 1 & 2 & 6 & 24 & 120 & 720 & 5040 & 40320 & 362880 & 3628800\\ 7 | \end{tabular}\\ 8 | \begin{tabular}{c|c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c} 9 | $n$ & 11 & 12 & 13 & 14 & 15 & 16 & 17\\ 10 | \hline 11 | $n!$ & 4.0e7 & 4.8e8 & 6.2e9 & 8.7e10 & 1.3e12 & 2.1e13 & 3.6e14\\ 12 | \end{tabular}\\ 13 | \begin{tabular}{c|c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c@{\ }c} 14 | $n$ & 20 & 25 & 30 & 40 & 50 & 100 & 150 & 171\\ 15 | \hline 16 | $n!$ & 2e18 & 2e25 & 3e32 & 8e47 & 3e64 & 9e157 & 6e262 & \scriptsize{$>$DBL\_MAX}\\ 17 | \end{tabular} 18 | \end{tabular} 19 | \end{center} -------------------------------------------------------------------------------- /Implementations/content/combinatorial (11.2)/rskverify: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bqi343/cp-notebook/292c614b7b83c355b188234966b3b336bc009f16/Implementations/content/combinatorial (11.2)/rskverify -------------------------------------------------------------------------------- /Implementations/content/contest/.bashrc: -------------------------------------------------------------------------------- 1 | alias clr="printf '\33c'" 2 | co() { g++ -std=c++17 -O2 -Wall -Wextra -Wshadow -Wconversion -o $1 $1.cpp; } 3 | run() { co $1 && ./$1; } -------------------------------------------------------------------------------- /Implementations/content/contest/.vimrc: -------------------------------------------------------------------------------- 1 | set cin aw ai is ts=4 sw=4 tm=50 nu noeb ru cul 2 | set mouse=a ww+=<,>,[,] 3 | sy on | im jk | im kj -------------------------------------------------------------------------------- /Implementations/content/contest/TemplateMinimal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | template using V = vector; 5 | #define all(x) begin(x), end(x) 6 | 7 | int main() { 8 | ios::sync_with_stdio(false); 9 | cin.tie(nullptr); 10 | 11 | } -------------------------------------------------------------------------------- /Implementations/content/contest/TemplateShort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | using ll = long long; 5 | using db = long double; // or double if tight TL 6 | using str = string; 7 | 8 | using pi = pair; 9 | #define mp make_pair 10 | #define f first 11 | #define s second 12 | 13 | #define tcT template using V = vector; 15 | tcT, size_t SZ> using AR = array; 16 | using vi = V; 17 | using vb = V; 18 | using vpi = V; 19 | 20 | #define sz(x) int((x).size()) 21 | #define all(x) begin(x), end(x) 22 | #define sor(x) sort(all(x)) 23 | #define rsz resize 24 | #define pb push_back 25 | #define ft front() 26 | #define bk back() 27 | 28 | #define FOR(i,a,b) for (int i = (a); i < (b); ++i) 29 | #define F0R(i,a) FOR(i,0,a) 30 | #define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i) 31 | #define R0F(i,a) ROF(i,0,a) 32 | #define rep(a) F0R(_,a) 33 | #define each(a,x) for (auto& a: x) 34 | 35 | const int MOD = 1e9+7; 36 | const db PI = acos((db)-1); 37 | mt19937 rng(0); // or mt19937_64 38 | 39 | tcT> bool ckmin(T& a, const T& b) { 40 | return b < a ? a = b, 1 : 0; } // set a = min(a,b) 41 | tcT> bool ckmax(T& a, const T& b) { 42 | return a < b ? a = b, 1 : 0; } // set a = max(a,b) 43 | 44 | int main() { cin.tie(0)->sync_with_stdio(0); } -------------------------------------------------------------------------------- /Implementations/content/contest/chapter.tex: -------------------------------------------------------------------------------- 1 | \chapter{Contest} 2 | 3 | \kactlimport[-l rawcpp]{TemplateShort.cpp} 4 | \kactlimport[-l sh]{.bashrc} 5 | % \kactlimport[-l raw]{.vimrc} 6 | \kactlimport[-l sh]{hash.sh} 7 | \kactlimport[-l sh]{stress.sh} 8 | \kactlimport[-l raw]{troubleshoot.txt} 9 | -------------------------------------------------------------------------------- /Implementations/content/contest/hash.sh: -------------------------------------------------------------------------------- 1 | # Hash file ignoring whitespace and comments. Verifies that 2 | # code was correctly typed. Usage: 'sh hash.sh < A.cpp' 3 | cpp -dD -P -fpreprocessed|tr -d '[:space:]'|md5sum|cut -c-6 -------------------------------------------------------------------------------- /Implementations/content/contest/old/CppIO_test.cpp: -------------------------------------------------------------------------------- 1 | int main() { 2 | // setIO(); 3 | { 4 | vector v = {0,1,1,0,1}; 5 | ps(v); 6 | bitset<5> b; b[3] = 1; 7 | ps(b); 8 | } 9 | { 10 | int a = 1; 11 | ll b = 2; 12 | db c = 3; 13 | char d = '4'; 14 | str e = "5"; 15 | bool f = true; 16 | complex g(1,2); 17 | ps("OK",a,b,c,d,e,f,g); 18 | } 19 | { 20 | pair a = {1, 2}; 21 | pair b = {"abcd", false}; 22 | pair c = {'x', 0.5}; 23 | string d = "This is a string"; 24 | pair > e = {1, {2, 3}}; 25 | dbg(a, b, c, d, e); 26 | dbg(); 27 | } 28 | { 29 | vector a = {1, 2, 3, 4}; 30 | set b = {1, 2, 2, 3, 3, 4, 4, 5}; 31 | map c; 32 | c["string 1"] = 1; 33 | c["string 2"] = 2; 34 | dbg(a, b, c); 35 | 36 | unordered_map d; 37 | d["string 3"] = 3; 38 | d["string 4"] = 4; 39 | multiset e = {5, 5, 4, 3, 1, 1, 2}; 40 | vector > f = {{1, 2, 3}}; 41 | dbg(d, e, f); 42 | } 43 | { 44 | int a = 1; 45 | int b = 2; 46 | dbg(a + b, a * b, a / b, a - b, a / (float)b, 2019, 2019 - 1); 47 | } 48 | } -------------------------------------------------------------------------------- /Implementations/content/contest/old/fstTrue_test.cpp: -------------------------------------------------------------------------------- 1 | int main() { 2 | FOR(lo,-20,21) FOR(hi,lo-1,21) { 3 | FOR(j,-40,41) { 4 | { 5 | int ans = lstTrue(lo,hi,[&](int x) { 6 | assert(lo <= x && x <= hi); 7 | return x <= j; 8 | }); 9 | assert(ans == min(hi,max(j,lo-1))); 10 | } 11 | { 12 | int ans = fstTrue(lo,hi,[&](int x) { 13 | assert(lo <= x && x <= hi); 14 | return x >= j; 15 | }); 16 | assert(ans == min(hi+1,max(j,lo))); 17 | } 18 | } 19 | } 20 | dbg("OK"); 21 | } -------------------------------------------------------------------------------- /Implementations/content/contest/old/genShort.py: -------------------------------------------------------------------------------- 1 | filenames = ['Template.cpp', 'CppIO.h', '../number-theory (11.1)/Modular Arithmetic/Modular.h'] 2 | debug = """void DBG() { cerr << "]" << endl; } 3 | template void DBG(H h, T... t) { 4 | cerr << h; if (sizeof...(t)) cerr << ", "; 5 | DBG(t...); } 6 | #ifdef LOCAL // compile with -DLOCAL 7 | #define dbg(...) cerr << "LINE(" << __LINE__ << ") -> [" << #__VA_ARGS__ << "]: [", DBG(__VA_ARGS__) 8 | #else 9 | #define dbg(...) 0 10 | #endif 11 | """ 12 | 13 | with open('TemplateShort.cpp', 'w') as outfile: 14 | with open('Template.cpp','r') as infile: 15 | ignore = False 16 | for line in infile: 17 | if not line.endswith('//\n'): 18 | if "// IGNORE" in line: 19 | ignore = not ignore 20 | continue 21 | if ignore: 22 | continue 23 | if "// 998244353" in line: 24 | line = line[:line.find("// 998244353")].rstrip()+"\n" 25 | # while len(line) >= 2 and line[-2] == ' ': 26 | # line = line[:-2]+'\n' 27 | if 'int main()' in line: 28 | outfile.write("\n"+debug+"\n") 29 | outfile.write(line) 30 | elif "mt19937" in line: 31 | outfile.write('mt19937 rng; // or mt19937_64\n') -------------------------------------------------------------------------------- /Implementations/content/contest/old/templateTest.cpp: -------------------------------------------------------------------------------- 1 | int main() { 2 | setIO(); 3 | FOR(i,-21,21) FOR(j,-21,21) if (j != 0) { 4 | db d = (db)i/j; 5 | assert(ceil(d) == cdiv(i,j)); 6 | assert(floor(d) == fdiv(i,j)); 7 | } 8 | } // test floor, ceiling division -------------------------------------------------------------------------------- /Implementations/content/contest/old/template_usaco_guide.cpp: -------------------------------------------------------------------------------- 1 | #include // see C++ Tips & Tricks 2 | using namespace std; 3 | 4 | using ll = long long; 5 | 6 | using vi = vector; 7 | #define pb push_back 8 | #define rsz resize 9 | #define all(x) begin(x), end(x) 10 | #define sz(x) (int)(x).size() 11 | 12 | using pi = pair; 13 | #define f first 14 | #define s second 15 | #define mp make_pair 16 | 17 | void setIO(string name = "") { // name is nonempty for USACO file I/O 18 | cin.tie(0)->sync_with_stdio(0); // see Fast Input & Output 19 | if (sz(name)) { 20 | freopen((name+".in").c_str(), "r", stdin); // see Input & Output 21 | freopen((name+".out").c_str(), "w", stdout); 22 | } 23 | } 24 | 25 | int main() { 26 | setIO(); 27 | 28 | } -------------------------------------------------------------------------------- /Implementations/content/contest/stress.sh: -------------------------------------------------------------------------------- 1 | # A and B are executables you want to compare, gen takes int 2 | # as command line arg. Usage: 'sh stress.sh' 3 | for((i = 1; ; ++i)); do 4 | echo $i 5 | ./gen $i > int 6 | ./A < int > out1 7 | ./B < int > out2 8 | diff -w out1 out2 || break 9 | # diff -w <(./A < int) <(./B < int) || break 10 | done -------------------------------------------------------------------------------- /Implementations/content/contest/templateKACTL.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define rep(i, a, b) for(int i = a; i < (b); ++i) 5 | #define each(a, x) for(auto& a : x) 6 | #define all(x) begin(x), end(x) 7 | #define sz(x) (int)(x).size() 8 | typedef long long ll; 9 | typedef pair pii; 10 | typedef vector vi; 11 | 12 | int main() { 13 | cin.sync_with_stdio(0); cin.tie(0); 14 | cin.exceptions(cin.failbit); 15 | } 16 | -------------------------------------------------------------------------------- /Implementations/content/data-structures/1D Range Queries (9.2)/BIT.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: Lukas Polacek 3 | * Date: 2009-10-30 4 | * License: CC0 5 | * Source: folklore/TopCoder 6 | * Description: Computes partial sums a[0] + a[1] + ... + a[pos - 1], and updates single elements a[i], 7 | * taking the difference between the old and new value. 8 | * Time: Both operations are $O(\log N)$. 9 | * Status: Stress-tested 10 | */ 11 | #pragma once 12 | 13 | tcT> struct BIT { 14 | int N; V data; 15 | void init(int _N) { N = _N; data.rsz(N); } 16 | void add(int p, T x) { for (++p;p<=N;p+=p&-p) data[p-1] += x; } 17 | T sum(int l, int r) { return sum(r+1)-sum(l); } 18 | T sum(int r) { T s = 0; for(;r;r-=r&-r)s+=data[r-1]; return s; } 19 | int lower_bound(T sum) { 20 | if (sum <= 0) return -1; 21 | int pos = 0; 22 | for (int pw = 1<<25; pw; pw >>= 1) { 23 | int npos = pos+pw; 24 | if (npos <= N && data[npos-1] < sum) 25 | pos = npos, sum -= data[pos-1]; 26 | } 27 | return pos; 28 | } 29 | }; -------------------------------------------------------------------------------- /Implementations/content/data-structures/1D Range Queries (9.2)/BIToff.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Offline BIT with coordinate copmpression. First do all 3 | * updates with $\texttt{mode=0}$ and then call $\texttt{init()}$. 4 | * Source: Own 5 | * Verification: https://codeforces.com/contest/1361/problem/F 6 | */ 7 | 8 | template struct BIToff { 9 | bool mode = 0; vi v; vector d; 10 | int atMost(int x) { return ub(all(v),x)-begin(v); } // how many <= x 11 | void upd(int x, T y) { 12 | if (!mode) { v.pb(x); return; } 13 | int p = atMost(x); assert(p && v[p-1] == x); 14 | for (;p<=sz(v);p+=p&-p) d[p] += y; 15 | } 16 | void init() { assert(!mode); mode = 1; 17 | sort(all(v)); v.erase(unique(all(v)),end(v)); d.rsz(sz(v)+1); } 18 | T sum(int x) { assert(mode); 19 | T ans = 0; for (int p=atMost(x);p;p-=p&-p) ans += d[p]; 20 | return ans; } 21 | T query(int x, int y) { return sum(y)-sum(x-1);} 22 | }; -------------------------------------------------------------------------------- /Implementations/content/data-structures/1D Range Queries (9.2)/BITrange.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: $D$-dimensional range increment and sum query with $2^D$ BITs, case $D=1$ 3 | * Source: https://www.geeksforgeeks.org/binary-indexed-tree-range-update-range-queries/ 4 | * Verification: CSES 5 | * Time: O(\log N) 6 | */ 7 | 8 | #include "BIT (9.2).h" 9 | 10 | template struct BITrange { 11 | BIT bit[2]; // piecewise linear functions 12 | // let cum[x] = sum_{i=1}^{x}a[i] 13 | void upd(int hi, T val) { // add val to a[1..hi] 14 | // if x <= hi, cum[x] += val*x 15 | bit[1].upd(1,val), bit[1].upd(hi+1,-val); 16 | // if x > hi, cum[x] += val*hi 17 | bit[0].upd(hi+1,hi*val); 18 | } 19 | void upd(int lo,int hi,T val){upd(lo-1,-val),upd(hi,val);} 20 | T sum(int x) { return bit[1].sum(x)*x+bit[0].sum(x); } 21 | T query(int x, int y) { return sum(y)-sum(x-1); } 22 | }; 23 | -------------------------------------------------------------------------------- /Implementations/content/data-structures/1D Range Queries (9.2)/BitNd.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: range sum queries and point updates for $D$ dimensions 3 | * Source: https://codeforces.com/blog/entry/64914 4 | * Verification: SPOJ matsum 5 | * Usage: \texttt{BIT} gives 2D BIT 6 | * Time: O((\log N)^D) 7 | */ 8 | 9 | template struct BIT { 10 | T val = 0; void upd(T v) { val += v; } 11 | T query() { return val; } 12 | }; 13 | template struct BIT { 14 | BIT bit[N+1]; 15 | template void upd(int pos, Args... args) { assert(pos > 0); 16 | for (; pos<=N; pos+=pos&-pos) bit[pos].upd(args...); } 17 | template T sum(int r, Args... args) { 18 | T res=0; for (;r;r-=r&-r) res += bit[r].query(args...); 19 | return res; } 20 | template T query(int l, int r, Args... 21 | args) { return sum(r,args...)-sum(l-1,args...); } 22 | }; 23 | template int get_kth(const BIT& bit, T des) { 24 | assert(des > 0); 25 | int ind = 0; 26 | for (int i = 1< struct ConsecutivePairs { 10 | set S; 11 | multiset difs; 12 | void ins_pair(T l, T r) { 13 | difs.ins(r-l); 14 | } 15 | void erase_pair(T l, T r) { 16 | auto it = difs.find(r-l); assert(it != end(difs)); 17 | difs.erase(it); 18 | } 19 | void ins(T t) { 20 | auto [it,inserted] = S.ins(t); assert(inserted); 21 | bool is_bg = it == bg(S), is_en = next(it) == end(S); 22 | if (!is_bg && !is_en) erase_pair(*prev(it),*next(it)); 23 | if (!is_bg) ins_pair(*prev(it),*it); 24 | if (!is_en) ins_pair(*it,*next(it)); 25 | } 26 | void erase(T t) { 27 | auto it = S.find(t); assert(it != end(S)); 28 | bool is_bg = it == bg(S), is_en = next(it) == end(S); 29 | if (!is_bg) erase_pair(*prev(it),*it); 30 | if (!is_en) erase_pair(*it,*next(it)); 31 | if (!is_bg && !is_en) ins_pair(*prev(it),*next(it)); 32 | S.erase(it); 33 | } 34 | void toggle(T t) { 35 | if (S.count(t)) erase(t); 36 | else ins(t); 37 | } 38 | }; -------------------------------------------------------------------------------- /Implementations/content/data-structures/1D Range Queries (9.2)/MaxQuery.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: insert pair $(a,b)$ and query max value 3 | * of $b$ over all pairs satisfying $a\ge x$. 4 | * Source: Own 5 | * Verification: https://codeforces.com/gym/102059/problem/K 6 | * http://www.usaco.org/index.php?page=viewproblem2&cpid=995 7 | * Time: O(\log N) 8 | */ 9 | 10 | struct MaxQuery { 11 | map m; 12 | void ins(int a, ll b) { 13 | auto it = m.lb(a); if (it != end(m) && it->s >= b) return; 14 | it = m.insert(it,{a,b}); it->s = b; 15 | while (it != begin(m) && prev(it)->s <= b) m.erase(prev(it)); 16 | } 17 | ll query(int x) { auto it = m.lb(x); 18 | return it == end(m) ? 0 : it->s; } 19 | }; -------------------------------------------------------------------------------- /Implementations/content/data-structures/1D Range Queries (9.2)/Mo (15.1).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Answers queries offline in (N+Q)sqrt(N) 3 | * Also see Mo's on trees 4 | * Source: Codeforces 5 | * Verification: https://codeforces.com/contest/617/problem/E 6 | */ 7 | 8 | int N, A[MX]; 9 | int ans[MX], oc[MX], BLOCK; 10 | V> todo; // store left, right, index of ans 11 | 12 | bool cmp(AR a, AR b) { // sort queries 13 | if (a[0]/BLOCK != b[0]/BLOCK) return a[0] < b[0]; 14 | return a[0]/BLOCK%2 ? a[1] < b[1] : a[1] > b[1]; 15 | } 16 | 17 | int l = 0, r = -1, cans = 0; 18 | 19 | void modify(int x, int y = 1) { 20 | x = A[x]; 21 | // if condition: --cans; 22 | oc[x] += y; 23 | // if condition: ++cans; 24 | } 25 | 26 | int answer(int L, int R) { // modifyjust interval 27 | while (l > L) modify(--l); 28 | while (r < R) modify(++r); 29 | while (l < L) modify(l++,-1); 30 | while (r > R) modify(r--,-1); 31 | return cans; 32 | } 33 | 34 | void solve() { 35 | BLOCK = sqrt(N); sort(all(todo),cmp); 36 | each(x,todo) { 37 | answer(x[0],x[1]); 38 | ans[x[2]] = cans; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Implementations/content/data-structures/1D Range Queries (9.2)/Wavelet.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: SegTree on values instead of indices. Returns $k$-th 3 | * largest number in 0-indexed interval \texttt{[lo,hi)}. 4 | * $SZ=2^p$ and all values in $a$ must lie in $[0,SZ)$. 5 | * Memory: O(N\log N) 6 | * Time: O(\log N) query 7 | * Source: http://rachitiitr.blogspot.com/2017/06 8 | /wavelet-trees-wavelet-trees-editorial.html 9 | * Verification: http://www.spoj.com/problems/MKTHNUM/ 10 | */ 11 | 12 | template struct Wavelet { 13 | vi nexl[SZ], nexr[SZ]; 14 | void build(vi a, int ind = 1, int L = 0, int R = SZ-1) { 15 | if (L == R) return; 16 | nexl[ind] = nexr[ind] = {0}; 17 | vi A[2]; int M = (L+R)/2; 18 | each(t,a) { 19 | A[t>M].pb(t); 20 | nexl[ind].pb(sz(A[0])), nexr[ind].pb(sz(A[1])); 21 | } 22 | build(A[0],2*ind,L,M), build(A[1],2*ind+1,M+1,R); 23 | } 24 | int query(int lo,int hi,int k,int ind=1,int L=0,int R=SZ-1) { 25 | if (L == R) return L; 26 | int M = (L+R)/2, t = nexl[ind][hi]-nexl[ind][lo]; 27 | if (t >= k) return query(nexl[ind][lo], 28 | nexl[ind][hi],k,2*ind,L,M); 29 | return query(nexr[ind][lo], 30 | nexr[ind][hi],k-t,2*ind+1,M+1,R); 31 | } 32 | }; 33 | -------------------------------------------------------------------------------- /Implementations/content/data-structures/2D Range Queries (15.2)/BITseg (15.2).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: BIT of SegTrees. $x\in (0,SZ), y\in [0,SZ)$. 3 | * Memory: O(N\log^2 N) 4 | * Source: USACO Mowing the Field 5 | * Verification: 6 | * USACO Mowing the Field 7 | * http://www.usaco.org/index.php?page=viewproblem2&cpid=722 (13/15, 15/15 and 1857ms with BumpAllocator) 8 | */ 9 | 10 | #include "../1D Range Queries (9.2)/SparseSeg (9.2).h" 11 | 12 | template struct BITseg { 13 | node seg[SZ]; 14 | BITseg() { F0R(i,SZ) seg[i] = node(); } 15 | void upd(int x, int y, int v) { // add v 16 | for (; x < SZ; x += x&-x) seg[x].upd(y,v); } 17 | T query(int x, int yl, int yr) { 18 | T res = 0; for (; x; x-=x&-x) res += seg[x].query(yl,yr); 19 | return res; } 20 | T query(int xl, int xr, int yl, int yr) { // query sum of rectangle 21 | return query(xr,yl,yr)-query(xl-1,yl,yr); } 22 | }; 23 | -------------------------------------------------------------------------------- /Implementations/content/data-structures/2D Range Queries (15.2)/BITtree (15.2).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: BIT of indexed sets (or treaps). $x\in (0,SZ)$. 3 | * Only supports setting value at each point to $0$ or $1$. 4 | * Memory: O(N\log N) 5 | * Verification: 6 | * http://codeforces.com/contest/785/submission/33953058 7 | * http://www.usaco.org/index.php?page=viewproblem2&cpid=722 (13/15) 8 | */ 9 | 10 | #include "../STL (5)/IndexedSet.h" 11 | 12 | template struct BITtree { 13 | Tree val[SZ]; 14 | void upd(int x, int y, int t = 1) { 15 | for (int X = x; X < SZ; X += X&-X) { 16 | if (t == 1) val[X].insert({y,x}); 17 | else val[X].erase({y,x}); 18 | } 19 | } 20 | int query(int x, int y) { 21 | int res = 0; for (; x; x -= x&-x) res += val[x].ook({y,MOD}); 22 | return res; 23 | } 24 | int query(int xl, int xr, int yl, int yr) { 25 | return query(xr,yr)-query(xl-1,yr) 26 | -query(xr,yl-1)+query(xl-1,yl-1); } 27 | }; 28 | -------------------------------------------------------------------------------- /Implementations/content/data-structures/LeftistHeap.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Persistent meldable heap. 3 | * Time: O(\log N) per meld 4 | * Memory: O(\log N) per meld 5 | * Source: 6 | * https://judge.yosupo.jp/submission/11843 7 | * https://en.wikipedia.org/wiki/Leftist_tree 8 | * Verification: See Kth Walk 9 | */ 10 | 11 | typedef pair T; 12 | typedef struct heap* ph; 13 | struct heap { // min heap 14 | ph l = NULL, r = NULL; 15 | int s = 0; T v; // s: path to leaf 16 | heap(T _v):v(_v) {} 17 | }; 18 | 19 | ph meld(ph p, ph q) { 20 | if (!p || !q) return p?:q; 21 | if (p->v > q->v) swap(p,q); 22 | ph P = new heap(*p); P->r = meld(P->r,q); 23 | if (!P->l || P->l->s < P->r->s) swap(P->l,P->r); 24 | P->s = (P->r?P->r->s:0)+1; return P; 25 | } 26 | ph ins(ph p, T v) { return meld(p, new heap(v)); } 27 | ph pop(ph p) { return meld(p->l,p->r); } -------------------------------------------------------------------------------- /Implementations/content/data-structures/README.md: -------------------------------------------------------------------------------- 1 | # Range Queries 2 | 3 | ## 5 4 | 5 | * Persistent Segment Tree 6 | * Tutorial 7 | * [Anudeep2011](https://blog.anudeep2011.com/persistent-segment-trees-explained-with-spoj-problems/) 8 | * [oml1111](https://drive.google.com/file/d/0BwGLW04WRv0ITEZjRWlMSFc2bk0/view) 9 | * [Lazy Propogation](http://codeforces.com/blog/entry/47108?#comment-315047) 10 | * Problems 11 | * [A2OJ](https://a2oj.com/category?ID=651) 12 | 13 | # 7 14 | 15 | * Treap 16 | * Notes 17 | * [Quora](https://threads-iiith.quora.com/Treaps-One-Tree-to-Rule-em-all-Part-1) 18 | * [PPT](https://docs.google.com/presentation/d/14xgtdDWnIBwmJRAuIdZ8FvLZcX9uRxnNoGOGAQRDIvc/edit?usp=sharing) 19 | * Samuel Hsiang Guide (see resources) 20 | * [Euler Tour Tree](https://codeforces.com/blog/entry/18369) 21 | * Problems 22 | * [Strings](https://csacademy.com/contest/archive/task/strings/) [](181) 23 | * [Points & Distances](https://www.hackerearth.com/problem/algorithm/septembereasy-points-and-distances-d30d0e6b/description/) [](185) 24 | * [Tree Rotations 2](https://szkopul.edu.pl/problemset/problem/b0BM0al2crQBt6zovEtJfOc6/site/?key=statement) [](193) 25 | * [A2OJ](https://a2oj.com/category?ID=14) 26 | -------------------------------------------------------------------------------- /Implementations/content/data-structures/STL (5)/CoordCompress.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: coordinate compression, get index of x by counting # of elements < x 3 | * Source: Own 4 | * Verification: ? 5 | */ 6 | 7 | template void nor(vector& v) { 8 | sort(all(v)); v.erase(unique(all(v)),end(v)); } 9 | template int ind(vector& v, T x) { 10 | return lb(all(v),x)-begin(v); } -------------------------------------------------------------------------------- /Implementations/content/data-structures/STL (5)/HashMap.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Hash map with similar API as unordered\_map. 3 | * Initial capacity must be a power of 2 if provided. 4 | * Source: KACTL 5 | * Memory: \tilde 1.5x unordered map 6 | * Time: \tilde 3x faster than unordered map 7 | * Usage: ht h({},{},{},{},{1<<16}); 8 | */ 9 | 10 | #include 11 | using namespace __gnu_pbds; 12 | struct chash { /// use most bits rather than just the lowest ones 13 | const uint64_t C = ll(4e18*acos(0))+71; // large odd number 14 | const int RANDOM = rng(); 15 | ll operator()(ll x) const { return __builtin_bswap64((x^RANDOM)*C); } 16 | }; /// https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html 17 | /// template using um = unordered_map; 18 | template using ht = gp_hash_table; 19 | template V get(ht& u, K x) { 20 | auto it = u.find(x); return it == end(u) ? 0 : it->s; } -------------------------------------------------------------------------------- /Implementations/content/data-structures/STL (5)/HashMapSmall.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Unordered map with keys in [0,SZ). (In case you're dumb like me and you need to replace a map rlly quickly ...) 3 | * Source: Own 4 | * Usage: HT dp; 5 | */ 6 | 7 | template struct HT { 8 | vi keys; bitset inside; T dat[SZ]; 9 | void clear() { 10 | each(t,keys) inside[t] = 0; 11 | keys.clear(); 12 | } 13 | T& operator[](int k) { 14 | if (!inside[k]) { 15 | inside[k] = 1, keys.pb(k); 16 | dat[k] = 0; 17 | } 18 | return dat[k]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Implementations/content/data-structures/STL (5)/MapComparator (5.2).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: example of function object (functor) for map or set 3 | * Source: StackOverflow 4 | * Usage: set s; map m; 5 | */ 6 | 7 | struct cmp{bool operator()(int l,int r)const{return l>r;}}; -------------------------------------------------------------------------------- /Implementations/content/data-structures/STL (5)/MinDeque (8.2).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: maintains minimum of deque while adding 3 | elements to back or deleting elements from front 4 | * Source: own 5 | * Verification: USACO Jan 18 Lifeguards 6 | */ 7 | 8 | template struct MinDeque { 9 | int lo = 0, hi = -1; 10 | deque> d; 11 | int size() { return hi-lo+1; } 12 | void push(T x) { // add to back 13 | while (sz(d) && d.back().f >= x) d.pop_back(); 14 | d.pb({x,++hi}); 15 | } 16 | void pop() { // delete from front 17 | assert(size()); 18 | if (d.front().s == lo++) d.pop_front(); 19 | } 20 | T mn() { return size() ? d.front().f : MOD; } 21 | // change MOD based on T 22 | }; -------------------------------------------------------------------------------- /Implementations/content/data-structures/STL (5)/OrderStatisticTree.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: A set (not multiset!) with support for finding the $n$'th 3 | * element, and finding the index of an element. Change \texttt{null\_type} to get a map. 4 | * Time: O(\log N) 5 | * Source: KACTL 6 | * https://codeforces.com/blog/entry/11080 7 | * Verification: many 8 | */ 9 | 10 | #include 11 | using namespace __gnu_pbds; 12 | tcT> using Tree = tree, 13 | rb_tree_tag, tree_order_statistics_node_update>; 14 | #define ook order_of_key 15 | #define fbo find_by_order 16 | 17 | void treeExample() { 18 | Tree t, t2; t.insert(8); 19 | auto it = t.insert(10).f; assert(it == t.lb(9)); 20 | assert(t.ook(10) == 1 && t.ook(11) == 2 && *t.fbo(0) == 8); 21 | t.join(t2); // assuming T < T2 or T > T2, merge t2 into t 22 | } 23 | 24 | /** 25 | int atMost(Tree& T, int r) { 26 | return T.ook({r,MOD}); } 27 | int getSum(Tree& T, int l, int r) { 28 | return atMost(T,r)-atMost(T,l-1); } 29 | */ 30 | -------------------------------------------------------------------------------- /Implementations/content/data-structures/STL (5)/PQ.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Priority queue w/ modification. Use for Dijkstra? 3 | * Source: https://gcc.gnu.org/onlinedocs/libstdc++/ext/pb_ds/pq_design.html 4 | * Verification: ? 5 | */ 6 | 7 | #include 8 | 9 | void pqExample() { 10 | __gnu_pbds::priority_queue p; 11 | vi act; vector v; 12 | int n = 1000000; 13 | F0R(i,n) { int r = rand(); act.pb(r), v.pb(p.push(r)); } 14 | F0R(i,n) { int r = rand(); act[i] = r, p.modify(v[i],r); } 15 | sort(rall(act)); 16 | F0R(i,n) { assert(act[i] == p.top()); p.pop(); } 17 | } 18 | -------------------------------------------------------------------------------- /Implementations/content/data-structures/STL (5)/Rope.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: insert element at $i$-th position, cut a substring and 3 | * re-insert somewhere else. At least 2 times slower than handwritten treap. 4 | * Time: O(\log N) per operation? not well tested 5 | * Source: https://codeforces.com/blog/entry/10355 6 | * Verification: CEOI 2018 Day 2 Triangles 7 | * https://szkopul.edu.pl/problemset/problem/AzKAZ2RDiVTjeWSBolwoC5zl/site/?key=statement 8 | * vector is faster for this problem ... 9 | */ 10 | 11 | #include 12 | using namespace __gnu_cxx; 13 | void ropeExample() { 14 | rope v(5,0); // initialize with 5 zeroes 15 | F0R(i,sz(v)) v.mutable_reference_at(i) = i+1; 16 | F0R(i,5) v.pb(i+1); // constant time pb 17 | rope cur = v.substr(1,2); 18 | v.erase(1,3); // erase 3 elements starting from 1st element 19 | for (rope::iterator it = v.mutable_begin(); 20 | it != v.mutable_end(); ++it) pr((int)*it,' '); 21 | ps(); // 1 5 1 2 3 4 5 22 | v.insert(v.mutable_begin()+2,cur); // or just 2 23 | v += cur; F0R(i,sz(v)) pr(v[i],' '); 24 | ps(); // 1 5 2 3 1 2 3 4 5 2 3 25 | } -------------------------------------------------------------------------------- /Implementations/content/data-structures/STL (5)/hashmap_old.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Avoid hacks with custom hash. 3 | * \texttt{gp\_hash\_table} is faster than \texttt{unordered\_map} 4 | * but uses more memory. 5 | * Source: 6 | * http://codeforces.com/blog/entry/62393 7 | * KACTL 8 | * Verification: http://codeforces.com/contest/966/problem/E 9 | * normal unordered map gets TLE 10 | */ 11 | 12 | #include 13 | using namespace __gnu_pbds; 14 | 15 | struct chash { 16 | static uint64_t splitmix64(uint64_t x) { 17 | // http://xorshift.di.unimi.it/splitmix64.c 18 | x += 0x9e3779b97f4a7c15; 19 | x = (x^(x >> 30)) * 0xbf58476d1ce4e5b9; 20 | x = (x^(x >> 27)) * 0x94d049bb133111eb; 21 | return x^(x >> 31); 22 | } 23 | size_t operator()(uint64_t x) const { 24 | static const uint64_t FIXED_RANDOM = 25 | chrono::steady_clock::now() 26 | .time_since_epoch().count(); 27 | return splitmix64(x+FIXED_RANDOM); 28 | } 29 | }; 30 | template using um = unordered_map; 31 | template using ht = gp_hash_table; 32 | template V get(ht& u, K x) { 33 | return u.find(x) == end(u) ? 0 : u[x]; } 34 | -------------------------------------------------------------------------------- /Implementations/content/data-structures/Static Range Queries (9.1)/FasterRMQ.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Faster 1D range minimum query. 3 | * Source: KACTL 4 | * Verification: 5 | * https://judge.yosupo.jp/submission/126814 6 | * Memory: O(N\log N) 7 | * Time: O(1) 8 | */ 9 | 10 | tcT, size_t SZ> struct RMQ { // floor(log_2(x)) 11 | static constexpr int level(int x) { return 31-__builtin_clz(x); } 12 | array, level(SZ)+1> jmp; 13 | T cmb(T a, T b) { return min(a, b); } 14 | void init(const V& v) { assert(sz(v) <= SZ); 15 | copy(all(v), begin(jmp[0])); 16 | for (int j = 1; 1< struct PrefixSums { 8 | vector> sum; 9 | void init(const vector>& v) { 10 | int R = sz(v), C = sz(v[0]); 11 | sum.assign(R+1,vector(C+1)); 12 | F0R(i,R) F0R(j,C) 13 | sum[i+1][j+1] = v[i][j]+sum[i+1][j]+sum[i][j+1]-sum[i][j]; 14 | } 15 | T get(int X1, int X2, int Y1, int Y2) { 16 | X2 ++, Y2 ++; 17 | return sum[X2][Y2]-sum[X1][Y2] 18 | -sum[X2][Y1]+sum[X1][Y1]; 19 | } 20 | }; 21 | -------------------------------------------------------------------------------- /Implementations/content/data-structures/Static Range Queries (9.1)/RMQ (9.1).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: 1D range minimum query. If TL is an issue, use 3 | * arrays instead of vectors and store values instead of indices. 4 | * Source: KACTL 5 | * Verification: 6 | * https://cses.fi/problemset/stats/1647/ 7 | * http://wcipeg.com/problem/ioi1223 8 | * https://pastebin.com/ChpniVZL 9 | * Memory: O(N\log N) 10 | * Time: O(1) 11 | */ 12 | 13 | tcT> struct RMQ { // floor(log_2(x)) 14 | int level(int x) { return 31-__builtin_clz(x); } 15 | V v; V jmp; 16 | int cmb(int a, int b) { 17 | return v[a]==v[b]?min(a,b):(v[a]& _v) { 19 | v = _v; jmp = {vi(sz(v))}; 20 | iota(all(jmp[0]),0); 21 | for (int j = 1; 1< struct RangeQuery { 9 | int n; 10 | T stor[SZ][32-__builtin_clz(SZ)], id = 1; 11 | vector a; 12 | T comb (T a, T b) { return mul(a,b); } // associative operation 13 | void fill(int l, int r, int ind) { 14 | if (ind < 0) return; 15 | int m = (l+r)/2; 16 | T prod = id; ROF(i,l,m) stor[i][ind] = prod = comb(a[i],prod); 17 | prod = id; FOR(i,m,r) stor[i][ind] = prod = comb(prod,a[i]); 18 | fill(l,m,ind-1); fill(m,r,ind-1); 19 | } 20 | void init() { 21 | n = 1; while ((1< SaVol(vP3 p, V faces) { 11 | T s = 0, v = 0; 12 | each(i,faces) { 13 | P3 a = p[i[0]], b = p[i[1]], c = p[i[2]]; 14 | s += abs(cross(a,b,c)); v += dot(cross(a,b),c); 15 | } 16 | return {s/2,v/6}; 17 | } 18 | -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Circles/Circle.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: represent circle as \{center,radius\} 3 | * Source: Own 4 | * Verification: see circle intersection 5 | */ 6 | 7 | #include "../Primitives/Point.h" 8 | 9 | using Circ = pair; 10 | int in(const Circ& x, const P& y) { // -1 if inside, 0, 1 11 | return sgn(abs(y-x.f)-x.s); } 12 | T arcLength(const Circ& x, P a, P b) { 13 | // precondition: a and b on x 14 | P d = (a-x.f)/(b-x.f); return x.s*acos(d.f); } -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Circles/CircleIsect.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Circle intersection points and intersection area. 3 | * Tangents will be returned twice. 4 | * Source: Own 5 | * also see http://mathworld.wolfram.com/Circle-CircleIntersection.html 6 | * Verification:https://codefights.com/tournaments/s8thqrnQL2YPK7XQt/L 7 | */ 8 | 9 | #include "Circle.h" 10 | 11 | vP isect(const Circ& x, const Circ& y) { // precondition: x!=y 12 | T d = abs(x.f-y.f), a = x.s, b = y.s; 13 | if (sgn(d) == 0) { assert(a != b); return {}; } 14 | T C = (a*a+d*d-b*b)/(2*a*d); 15 | if (abs(C) > 1+EPS) return {}; 16 | T S = sqrt(max(1-C*C,(T)0)); P tmp = (y.f-x.f)/d*x.s; 17 | return {x.f+tmp*P(C,S),x.f+tmp*P(C,-S)}; 18 | } 19 | vP isect(const Circ& x, const Line& y) { 20 | P c = foot(x.f,y); T sq_dist = sq(x.s)-abs2(x.f-c); 21 | if (sgn(sq_dist) < 0) return {}; 22 | P offset = unit(y.s-y.f)*sqrt(max(sq_dist,T(0))); 23 | return {c+offset,c-offset}; 24 | } 25 | T isect_area(Circ x, Circ y) { // not thoroughly tested 26 | T d = abs(x.f-y.f), a = x.s, b = y.s; if (a < b) swap(a,b); 27 | if (d >= a+b) return 0; 28 | if (d <= a-b) return PI*b*b; 29 | T ca = (a*a+d*d-b*b)/(2*a*d), cb = (b*b+d*d-a*a)/(2*b*d); 30 | T s = (a+b+d)/2, h = 2*sqrt(s*(s-a)*(s-b)*(s-d))/d; 31 | return a*a*acos(ca)+b*b*acos(cb)-d*h; 32 | } -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Circles/CircleTangents.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: internal and external tangents between two circles 3 | * Source: Own 4 | * Verification: USACO Laser Cows 5 | */ 6 | 7 | #include "Circle.h" 8 | 9 | P tangent(P x, Circ y, int t = 0) { 10 | y.s = abs(y.s); // abs needed because internal calls y.s < 0 11 | if (y.s == 0) return y.f; 12 | T d = abs(x-y.f); 13 | P a = pow(y.s/d,2)*(x-y.f)+y.f; 14 | P b = sqrt(d*d-y.s*y.s)/d*y.s*unit(x-y.f)*dir(PI/2); 15 | return t == 0 ? a+b : a-b; 16 | } 17 | V> external(Circ x, Circ y) { 18 | V> v; 19 | if (x.s == y.s) { 20 | P tmp = unit(x.f-y.f)*x.s*dir(PI/2); 21 | v.eb(x.f+tmp,y.f+tmp); 22 | v.eb(x.f-tmp,y.f-tmp); 23 | } else { 24 | P p = (y.s*x.f-x.s*y.f)/(y.s-x.s); 25 | F0R(i,2) v.eb(tangent(p,x,i),tangent(p,y,i)); 26 | } 27 | return v; 28 | } 29 | V> internal(Circ x, Circ y) { 30 | return external({x.f,-x.s},y); } 31 | -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Circles/Circumcenter.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: returns \{circumcenter,circumradius\} 3 | * Source: EGMO 4 | * Verification: see MEC 5 | */ 6 | 7 | #include "Circle.h" 8 | 9 | Circ ccCenter(P a, P b, P c) { 10 | b -= a; c -= a; 11 | P res = b*c*(conj(c)-conj(b))/(b*conj(c)-conj(b)*c); 12 | return {a+res,abs(res)}; 13 | } 14 | -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Circles/MinEnclosingCirc.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: minimum enclosing circle 3 | * Time: expected $O(N)$ 4 | * Source: KACTL 5 | * Verification: USACO Camp 2019 Contest 2 #4 6 | */ 7 | 8 | #include "Circumcenter.h" 9 | 10 | circ mec(vP ps) { 11 | shuffle(all(ps), rng); 12 | P o = ps[0]; T r = 0, EPS = 1+1e-8; 13 | F0R(i,sz(ps)) if (abs(o-ps[i]) > r*EPS) { 14 | o = ps[i], r = 0; // point is on MEC 15 | F0R(j,i) if (abs(o-ps[j]) > r*EPS) { 16 | o = (ps[i]+ps[j])/2, r = abs(o-ps[i]); 17 | F0R(k,j) if (abs(o-ps[k]) > r*EPS) 18 | tie(o,r) = ccCenter(ps[i],ps[j],ps[k]); 19 | } 20 | } 21 | return {o,r}; 22 | } 23 | -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Misc/ClosestPair (13.2).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Line sweep to find two closest points . 3 | * Time: O(N\log N) 4 | * Source: Own 5 | * Verification: https://open.kattis.com/problems/closestpair2 6 | */ 7 | 8 | #include "../Primitives/Point.h" 9 | 10 | pair solve(vP v) { 11 | pair> bes; bes.f = INF; 12 | set

S; int ind = 0; 13 | sort(all(v)); 14 | F0R(i,sz(v)) { 15 | if (i && v[i] == v[i-1]) return {v[i],v[i]}; 16 | for (; v[i].f-v[ind].f >= bes.f; ++ind) 17 | S.erase({v[ind].s,v[ind].f}); 18 | for (auto it = S.ub({v[i].s-bes.f,INF}); 19 | it != end(S) && it->f < v[i].s+bes.f; ++it) { 20 | P t = {it->s,it->f}; 21 | ckmin(bes,{abs(t-v[i]),{t,v[i]}}); 22 | } 23 | S.insert({v[i].s,v[i].f}); 24 | } 25 | return bes.s; 26 | } 27 | -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Misc/Delaunay3.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Delaunay triangulation with 3D hull. Assumes no duplicate points 3 | * and that not all points are collinear. If coordinates are ints at most $B$, 4 | * \texttt{T} should be large enough to support ints on the order of $B^4$. 5 | * Time: O(N\log N) 6 | * Source: KACTL 7 | * Verification: 8 | * https://dmoj.ca/problem/cco08p6 9 | */ 10 | 11 | #include "../Primitives/Point.h" 12 | #include "Hull3D.h" 13 | 14 | V> triHull(vP p) { 15 | V p3; V> res; each(x,p) p3.pb({x.f,x.s,abs2(x)}); 16 | bool ok = 0; each(t,p3) ok |= !coplanar(p3[0],p3[1],p3[2],t); 17 | if (!ok) { // all points concyclic 18 | sort(1+all(p),[&p](P a, P b) { 19 | return cross(a-p.ft,b-p.ft)>0; }); 20 | FOR(i,1,sz(p)-1) res.pb({p.ft,p[i],p[i+1]}); 21 | } else { 22 | #define nor(x) P(p3[x][0],p3[x][1]) 23 | each(t,hull3dFast(p3)) 24 | if (dot(cross(p3[t[0]],p3[t[1]],p3[t[2]]),{0,0,1}) < 0) 25 | res.pb({nor(t[0]),nor(t[2]),nor(t[1])}); 26 | } 27 | return res; 28 | } 29 | -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Misc/ManhattanMST.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Given $N$ points, returns up to $4N$ edges which are guaranteed 3 | * to contain a MST for graph with edge weights $w(p,q) =|p.x-q.x|+|p.y-q.y|.$ 4 | * Edges are in the form \texttt{\{dist, \{src, dst\}\}}. 5 | * Time: O(N\log N) 6 | * Source: KACTL 7 | * https://github.com/spaghetti-source/algorithm/blob/master/geometry/rectilinear_mst.cc 8 | * Verification: https://open.kattis.com/problems/gridmst 9 | */ 10 | 11 | #include "DSU (7.6).h" 12 | 13 | // use standard MST algorithm on result to find final MST 14 | V> manhattanMst(vpi v) { 15 | vi id(sz(v)); iota(all(id),0); 16 | V> ed; 17 | F0R(k,4) { 18 | sort(all(id),[&](int i, int j) { 19 | return v[i].f+v[i].s < v[j].f+v[j].s; }); 20 | map sweep; // find first octant neighbors 21 | each(i,id) { // those in sweep haven't found neighbor yet 22 | for (auto it = sweep.lb(-v[i].s); 23 | it != end(sweep); sweep.erase(it++)) { 24 | int j = it->s; 25 | pi d{v[i].f-v[j].f,v[i].s-v[j].s};if (d.s>d.f)break; 26 | ed.pb({d.f+d.s,{i,j}}); 27 | } 28 | sweep[-v[i].s] = i; 29 | } 30 | each(p,v) { 31 | if (k&1) p.f *= -1; 32 | else swap(p.f,p.s); 33 | } 34 | } 35 | return ed; 36 | } 37 | -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Misc/MaxCollinear.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Compute the maximum number of points which lie on the same line in O(n^2logn) 3 | * Source: own 4 | * Verification: https://open.kattis.com/problems/maxcolinear 5 | */ 6 | 7 | pair getline(pi a, pi b) { 8 | pi z = {b.f-a.f,b.s-a.s}; 9 | swap(z.f,z.s); z.f *= -1; 10 | int g = gcd(z.f,z.s); z.f /= g, z.s /= g; 11 | ckmin(z,{-z.f,-z.s}); 12 | return {z,z.f*a.f+z.s*a.s}; 13 | } 14 | 15 | int solve(vpi p) { 16 | int n = sz(p); 17 | map,int> m; 18 | F0R(i,n) FOR(j,i+1,n) ++m[getline(p[i],p[j])]; 19 | int mx = 0; each(a,m) ckmax(mx,a.s); 20 | int ans = 0; FOR(i,1,n+1) if (i*(i-1)/2 <= mx) ans = i; 21 | return ans; 22 | } 23 | -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Polygons/ConvexHull (13.2).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: top-bottom convex hull 3 | * Time: O(N\log N) 4 | * Source: Wikibooks, KACTL 5 | * Verification: 6 | * https://open.kattis.com/problems/convexhull 7 | */ 8 | 9 | #include "../Primitives/Point.h" 10 | 11 | pair ulHull(const vP& v) { 12 | vi p(sz(v)), u, l; iota(all(p), 0); 13 | sort(all(p), [&v](int a, int b) { return v[a] < v[b]; }); 14 | each(i,p) { 15 | #define ADDP(C, cmp) while (sz(C) > 1 && cross(\ 16 | v[C[sz(C)-2]],v[C.bk],v[i]) cmp 0) C.pop_back(); C.pb(i); 17 | ADDP(u, >=); ADDP(l, <=); 18 | } 19 | return {u,l}; 20 | } 21 | vi hullInd(const vP& v) { // returns indices in CCW order 22 | vi u,l; tie(u,l) = ulHull(v); if (sz(l) <= 1) return l; 23 | if (v[l[0]] == v[l[1]]) return {0}; 24 | l.insert(end(l),1+rall(u)-1); return l; 25 | } 26 | vP hull(const vP& v) { 27 | vi w = hullInd(v); vP res; each(t,w) res.pb(v[t]); 28 | return res; } -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Polygons/ConvexHullGraham.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Graham Scan 3 | * Time: O(N\log N) 4 | * Source: Own 5 | * Verification: 6 | * https://open.kattis.com/problems/convexhull 7 | */ 8 | 9 | #include "../Primitives/Point.h" 10 | 11 | /// typedef ll T; 12 | vi hullInd(const vP& v) { 13 | int ind = int(min_element(all(v))-begin(v)); 14 | vi cand, C{ind}; F0R(i,sz(v)) if (v[i] != v[ind]) cand.pb(i); 15 | sort(all(cand),[&](int a, int b) { 16 | // sort by angle, tiebreak by distance 17 | P x = v[a]-v[ind], y = v[b]-v[ind]; T t = cross(x,y); 18 | return t != 0 ? t > 0 : abs2(x) < abs2(y); }); 19 | each(c,cand) { 20 | while (sz(C) > 1 && cross(v[end(C)[-2]],v[C.bk],v[c]) <= 0) 21 | C.pop_back(); 22 | C.pb(c); } 23 | return C; 24 | } 25 | /**vP hull(const vP& v) { 26 | vi w = hullInd(v); vP res; each(t,w) res.pb(v[t]); 27 | return res; }*/ 28 | -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Polygons/HullDiameter.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Rotating caliphers. Returns square of greatest distance 3 | * between two points in $P$. 4 | * Time: $O(N)$ given convex hull 5 | * Source: KACTL 6 | * Verification: https://open.kattis.com/problems/roberthood 7 | */ 8 | 9 | #include "ConvexHull (13.2).h" 10 | 11 | db diameter2(vP P) { 12 | P = hull(P); 13 | int n = sz(P), ind = 1; T ans = 0; 14 | if (n > 1) F0R(i,n) for (int j = (i+1)%n;;ind = (ind+1)%n) { 15 | ckmax(ans, abs2(P[i]-P[ind])); 16 | if (cross(P[j]-P[i],P[(ind+1)%n]-P[ind]) <= 0) break; 17 | } 18 | return ans; 19 | } 20 | -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Polygons/HullTangents.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Given convex polygon with no three points collinear and a point 3 | * strictly outside of it, computes the lower and upper tangents. 4 | * Source: Own 5 | * Time: O(\log N) 6 | * Verification: tested 7 | */ 8 | 9 | #include "../Primitives/Point.h" 10 | 11 | bool lower; 12 | bool better(P a, P b, P c) { 13 | T z = cross(a,b,c); 14 | return lower ? z < 0 : z > 0; } 15 | int tangent(const vP& a, P b) { 16 | if (sz(a) == 1) return 0; 17 | int lo, hi; 18 | if (better(b,a[0],a[1])) { 19 | lo = 0, hi = sz(a)-1; 20 | while (lo < hi) { 21 | int mid = (lo+hi+1)/2; 22 | if (better(b,a[0],a[mid])) lo = mid; 23 | else hi = mid-1; 24 | } 25 | lo = 0; 26 | } else { 27 | lo = 1, hi = sz(a); 28 | while (lo < hi) { 29 | int mid = (lo+hi)/2; 30 | if (!better(b,a[0],a[mid])) lo = mid+1; 31 | else hi = mid; 32 | } 33 | hi = sz(a); 34 | } 35 | while (lo < hi) { 36 | int mid = (lo+hi)/2; 37 | if (better(b,a[mid],a[(mid+1)%sz(a)])) lo = mid+1; 38 | else hi = mid; 39 | } 40 | return lo%sz(a); 41 | } 42 | pi tangents(const vP& a, P b) { 43 | lower = 1; int x = tangent(a,b); 44 | lower = 0; int y = tangent(a,b); 45 | return {x,y}; 46 | } -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Polygons/InPolygon.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Tests whether point is inside, on, or outside of a polygon 3 | * (returns -1, 0, or 1). Both CW and CCW polygons are ok. 4 | * Time: O(N) 5 | * Verification: https://open.kattis.com/problems/pointinpolygon 6 | */ 7 | 8 | #include "../Primitives/Point.h" 9 | 10 | int inPoly(const P& p, const vP& poly) { 11 | int n = sz(poly), ans = 0; 12 | F0R(i,n) { 13 | P x = poly[i], y = poly[(i+1)%n]; if (x.s > y.s) swap(x,y); 14 | if (onSeg(p,{x,y})) return 0; 15 | ans ^= (x.s <= p.s && p.s < y.s && cross(p,x,y) > 0); 16 | } 17 | return ans ? -1 : 1; 18 | } -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Polygons/MinkowskiSum.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Minkowski sum of two convex polygons given in CCW order. 3 | * Time: O(N) 4 | * Source: https://cp-algorithms.com/geometry/minkowski.html#implementation 5 | * Verification: 6 | * MITPC 7 | * https://open.kattis.com/problems/roberthood 8 | */ 9 | 10 | #include "ConvexHull.h" 11 | 12 | vP minkowski_sum(vP a, vP b) { 13 | if (sz(a) > sz(b)) swap(a, b); 14 | if (!sz(a)) return {}; 15 | if (sz(a) == 1) { 16 | each(t, b) t += a.ft; 17 | return b; 18 | } 19 | rotate(begin(a), min_element(all(a)), end(a)); 20 | rotate(begin(b), min_element(all(b)), end(b)); 21 | a.pb(a[0]), a.pb(a[1]); 22 | b.pb(b[0]), b.pb(b[1]); 23 | vP result; 24 | int i = 0, j = 0; 25 | while (i < sz(a)-2 || j < sz(b)-2) { 26 | result.pb(a[i]+b[j]); 27 | T crs = cross(a[i+1]-a[i],b[j+1]-b[j]); 28 | i += (crs >= 0); 29 | j += (crs <= 0); 30 | } 31 | return result; 32 | } 33 | 34 | T diameter2(vP p) { // example application: squared diameter 35 | vP a = hull(p); 36 | vP b = a; each(t, b) t *= -1; 37 | vP c = minkowski_sum(a, b); 38 | T ret = 0; each(t, c) ckmax(ret, abs2(t)); 39 | return ret; 40 | } -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Polygons/PolygonCenArea.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: centroid (center of mass) of a polygon with 3 | * constant mass per unit area and SIGNED area 4 | * Time: O(N) 5 | * Source: http://codeforces.com/blog/entry/22175, KACTL 6 | * Verification: kattis polygonarea, VT HSPC 2018 Holiday Stars 7 | */ 8 | 9 | #include "../Primitives/Point.h" 10 | 11 | pair cenArea(const vP& v) { assert(sz(v) >= 3); 12 | P cen{}; T area{}; 13 | F0R(i,sz(v)) { 14 | int j = (i+1)%sz(v); T a = cross(v[i],v[j]); 15 | cen += a*(v[i]+v[j]); area += a; } 16 | return {cen/area/(T)3,area/2}; // area is SIGNED 17 | } -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Primitives/AngleCmp.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Sorts points in ccw order about origin in the same way as 3 | * \texttt{atan2}, which returns real in $(-\pi,\pi]$ so points on 4 | * negative $x$-axis come last. 5 | * Verification: https://codeforces.com/contest/1284/submission/68175790 6 | * https://codeforces.com/contest/1284/submission/68207607 7 | * (don't use atan2, weird stuff happens!) 8 | * Usage: vP v; sort(all(v),angleCmp); 9 | */ 10 | 11 | #include "Point.h" 12 | 13 | // WARNING: you will get unexpected results if you mistype this as bool instead of int 14 | // -1 if lower half, 0 if origin, 1 if upper half 15 | int half(P x) { return x.s != 0 ? sgn(x.s) : -sgn(x.f); } 16 | bool angleCmp(P a, P b) { int A = half(a), B = half(b); 17 | return A == B ? cross(a,b) > 0 : A < B; } 18 | 19 | // equivalent to: sort(all(v),[](P a, P b) { 20 | // return atan2(a.s,a.f) < atan2(b.s,b.f); }); -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Primitives/Complex.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Easy geo. 3 | * Source: http://codeforces.com/blog/entry/22175, KACTL 4 | * https://codeforces.com/blog/entry/22175#comment-582178 5 | * Verification: various 6 | */ 7 | 8 | using T = db; 9 | int sgn(T a) { return (a>0)-(a<0); } 10 | T sq(T a) { return a*a; } 11 | 12 | #define x real() 13 | #define y imag() 14 | typedef complex P; typedef vector

vP; 15 | namespace std { // take care of comparisons 16 | bool operator<(P l, P r) { return mp(l.x,l.y) < mp(r.x,r.y); } } 17 | P dir(T ang) { return polar((T)1,ang); } 18 | P unit(P p) { return p/abs(p); } 19 | T dot(P a, P b) { return a.x*b.x+a.y*b.y; } 20 | T cross(P a, P b) { return a.x*b.y-a.y*b.x; } 21 | T cross(P p, P a, P b) { return cross(a-p,b-p); } 22 | P reflect(P p,P a,P b) { return a+conj((p-a)/(b-a))*(b-a); } 23 | P foot(P p, P a, P b) { return (p+reflect(p,a,b))/(T)2; } 24 | bool onSeg(P p, P a, P b) { 25 | return cross(a,b,p) == 0 && dot(p-a,p-b) <= 0; } -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Primitives/ComplexComp.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Allows you to sort complex numbers. 3 | * Source: http://codeforces.com/blog/entry/22175, KACTL 4 | * https://codeforces.com/blog/entry/22175#comment-582178 5 | * Verification: various 6 | */ 7 | 8 | #define x real() 9 | #define y imag() 10 | using P = complex; 11 | namespace std { 12 | bool operator<(P l,P r) { return mp(l.x,l.y) v = {{4,5},{3,6},{5,7}}; sort(all(v)); ps(v); -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Primitives/SegDist.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: computes distance between $P$ and line (segment) $AB$ 3 | * Source: own 4 | * Verification: https://open.kattis.com/problems/segmentdistance 5 | */ 6 | 7 | #include "Point.h" 8 | 9 | T lineDist(const P& p, const Line& l) { 10 | return abs(cross(p,l.f,l.s))/abs(l.f-l.s); } 11 | T segDist(const P& p, const Line& l) { 12 | if (dot(l.f,p,l.s) <= 0) return abs(p-l.f); 13 | if (dot(l.s,p,l.f) <= 0) return abs(p-l.s); 14 | return lineDist(p,l); } -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/Primitives/SegIsect.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: computes the intersection point(s) of line (segments) $a$ and $b$ 3 | * Source: KACTL 4 | * Verification: https://open.kattis.com/problems/segmentintersection 5 | */ 6 | 7 | #include "Point.h" 8 | 9 | // {unique intersection point} if it exists 10 | // {b.f,b.s} if input lines are the same 11 | // empty if lines do not intersect 12 | vP lineIsect(const Line& a, const Line& b) { 13 | T a0 = cross(a.f,a.s,b.f), a1 = cross(a.f,a.s,b.s); 14 | if (a0 == a1) return a0 == 0 ? vP{b.f,b.s} : vP{}; 15 | return {(b.s*a0-b.f*a1)/(a0-a1)}; 16 | } 17 | 18 | // point in interior of both segments a and b, if it exists 19 | vP strictIsect(const Line& a, const Line& b) { 20 | T a0 = cross(a.f,a.s,b.f), a1 = cross(a.f,a.s,b.s); 21 | T b0 = cross(b.f,b.s,a.f), b1 = cross(b.f,b.s,a.s); 22 | if (sgn(a0)*sgn(a1) < 0 && sgn(b0)*sgn(b1) < 0) 23 | return {(b.s*a0-b.f*a1)/(a0-a1)}; 24 | return {}; 25 | } 26 | 27 | // intersection of segments, a and b may be degenerate 28 | vP segIsect(const Line& a, const Line& b) { 29 | vP v = strictIsect(a,b); if (sz(v)) return v; 30 | set

s; 31 | #define i(x,y) if (onSeg(x,y)) s.ins(x) 32 | i(a.f,b); i(a.s,b); i(b.f,a); i(b.s,a); 33 | return {all(s)}; 34 | } 35 | -------------------------------------------------------------------------------- /Implementations/content/geometry (13)/README.md: -------------------------------------------------------------------------------- 1 | # Geometry (Advanced) 2 | 3 | * [KD Tree](https://github.com/kth-competitive-programming/kactl/blob/master/content/geometry/kdTree.h) 4 | * haven't had to use ... 5 | * Delaunay Triangulation 6 | * Tutorial 7 | * [Paper](http://www.sccg.sk/~samuelcik/dgs/quad_edge.pdf) 8 | * [Slides](http://graphics.stanford.edu/courses/cs368-06-spring/handouts/Delaunay_2.pdf) 9 | * [CP-Algo](https://cp-algorithms.com/geometry/delaunay.html) 10 | * [KACTL](https://github.com/kth-competitive-programming/kactl/blob/master/content/geometry/FastDelaunay.h) 11 | * Problems 12 | * [CCO 2008 Landing](https://dmoj.ca/problem/cco08p6) 13 | * [Panda Preserve](https://icpc.kattis.com/problems/pandapreserve) 14 | * [Geometry Special Contest](https://codeforces.com/gym/101793) 15 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Basics/BellmanFord (7.3).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Shortest Path w/ negative edge weights 3 | * Can be useful with linear programming 4 | * Constraints of the form x_i-x_j struct BellmanFord { 12 | int n; 13 | vi adj[SZ]; 14 | V> ed; 15 | void ae(int u, int v, int w) { 16 | adj[u].pb(v), ed.pb({{u,v},w}); } 17 | ll dist[SZ]; 18 | void genBad(int x) { 19 | // if x is reachable from negative cycle 20 | // -> update dists of all vertices which x can go to 21 | if (dist[x] == -INF) return; 22 | dist[x] = -INF; 23 | each(t,adj[x]) genBad(t); 24 | } 25 | void init(int _n, int s) { 26 | n = _n; F0R(i,n) dist[i] = INF; 27 | dist[s] = 0; 28 | F0R(i,n) each(a,ed) if (dist[a.f.f] < INF) 29 | ckmin(dist[a.f.s],dist[a.f.f]+a.s); 30 | each(a,ed) if (dist[a.f.f] < INF 31 | && dist[a.f.s] > dist[a.f.f]+a.s) 32 | genBad(a.f.s); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Basics/Dijkstra (7.3).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: shortest path 3 | * Source: own 4 | * Verification: https://open.kattis.com/problems/shortestpath1 5 | */ 6 | 7 | template struct Dijkstra { 8 | int SZ; V dist; 9 | V>> adj; 10 | void init(int _SZ) { SZ = _SZ; adj.clear(); adj.rsz(SZ); } 11 | void ae(int u, int v, C cost) { 12 | adj[u].pb({v,cost}); if (!directed) adj[v].pb({u,cost}); } 13 | void gen(int st) { 14 | dist.assign(SZ,numeric_limits::max()); 15 | using T = pair; pqg pq; 16 | auto ad = [&](int a, C b) { 17 | if (dist[a] <= b) return; 18 | pq.push({dist[a] = b,a}); 19 | }; ad(st,0); 20 | while (sz(pq)) { 21 | T x = pq.top(); pq.pop(); if (dist[x.s] < x.f) continue; 22 | each(y,adj[x.s]) ad(y.f,x.f+y.s); 23 | } 24 | } 25 | }; 26 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Basics/DirectedCycle.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: stack 3 | * Source: https://www.geeksforgeeks.org/detect-cycle-in-a-graph/ 4 | * Verification: VT HSPC 2019 D 5 | */ 6 | 7 | template struct DirCyc { 8 | vi adj[SZ], stk, cyc; vb inStk, vis; 9 | void dfs(int x) { 10 | stk.pb(x); inStk[x] = vis[x] = 1; 11 | each(i,adj[x]) { 12 | if (inStk[i]) cyc = {find(all(stk),i),end(stk)}; 13 | else if (!vis[i]) dfs(i); 14 | if (sz(cyc)) return; 15 | } 16 | stk.pop_back(); inStk[x] = 0; 17 | } 18 | vi init(int N) { 19 | inStk.rsz(N), vis.rsz(N); 20 | F0R(i,N) if (!vis[i] && !sz(cyc)) dfs(i); 21 | return cyc; 22 | } 23 | }; 24 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Basics/FloydWarshall (7.3).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: All-Pairs Shortest Path 3 | * Source: KACTL 4 | * Verification: 5 | * https://open.kattis.com/problems/allpairspath 6 | * https://cses.fi/problemset/task/1672/ 7 | */ 8 | 9 | void floydWarshall(V& m) { 10 | int n = sz(m); 11 | F0R(i,n) ckmin(m[i][i], 0LL); 12 | F0R(k,n) F0R(i,n) F0R(j,n) 13 | if (m[i][k] != BIG && m[k][j] != BIG) { 14 | auto newDist = max(m[i][k]+m[k][j],-BIG); 15 | ckmin(m[i][j],newDist); 16 | } 17 | F0R(k,n) if (m[k][k] < 0) F0R(i,n) F0R(j,n) 18 | if (m[i][k] != BIG && m[k][j] != BIG) m[i][j] = -BIG; 19 | } -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Basics/GridBFS (7.2).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: BFS through grid with fixed xdir and ydir arrays 3 | * Source: Own 4 | */ 5 | 6 | const int xdir[4] = {0,1,0,-1}, ydir[4] = {1,0,-1,0}; 7 | int dist[21][21]; 8 | 9 | bool valid(pi y) { 10 | return !(y.f < 0 || y.f > 20 || y.s < 0 || y.s > 20); // this point is outside of grid 11 | } 12 | 13 | void bfs() { 14 | F0R(i,21) F0R(j,21) dist[i][j] = MOD; 15 | dist[10][10] = 0; 16 | 17 | queue todo; todo.push({10,10}); // initialize queue, distances 18 | while (sz(todo)) { 19 | pi x = todo.front(); todo.pop(); // pop point from queue 20 | F0R(i,4) { 21 | pi y = {x.f+xdir[i],x.s+ydir[i]}; 22 | if (!valid(y)) continue; 23 | if (dist[y.f][y.s] == MOD) { // test whether point has been visited or not 24 | dist[y.f][y.s] = dist[x.f][x.s]+1; 25 | todo.push(y); // push point to queue 26 | } 27 | } 28 | } 29 | 30 | assert(dist[4][5] == 11); 31 | } 32 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Basics/NegativeCycle (7.3).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: use Bellman-Ford (make sure no underflow) 3 | * Source: https://cp-algorithms.com/graph/finding-negative-cycle-in-graph.html 4 | * Verification: https://cses.fi/problemset/task/1197/ 5 | */ 6 | 7 | vi negCyc(int N, V> ed) { 8 | vl d(N); vi p(N); int x = -1; 9 | rep(N) { 10 | x = -1; each(t,ed) if (ckmin(d[t.f.s],d[t.f.f]+t.s)) 11 | p[t.f.s] = t.f.f, x = t.f.s; 12 | if (x == -1) return {}; 13 | } 14 | rep(N) x = p[x]; // enter cycle 15 | vi cyc{x}; while (p[cyc.bk] != x) cyc.pb(p[cyc.bk]); 16 | reverse(all(cyc)); return cyc; 17 | } 18 | 19 | /** 20 | Explanation: 21 | 22 | If we follow the links back from t.f.s then we must always enter a cycle. 23 | Otherwise, this would contradict the assumption that there exists a shorter 24 | path to t.f.s when considering paths of arbitrary length than those of 25 | length at most n-1. The sum of the edge weights along this path is 26 | non-positive, and it can't be zero because then it would have no origin ... 27 | */ 28 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Basics/TopoSort (7.4).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: sorts vertices such that if there exists an edge x->y, then x goes before y 3 | * Source: KACTL 4 | * Verification: https://open.kattis.com/problems/quantumsuperposition 5 | */ 6 | 7 | struct TopoSort { 8 | int N; vi in, res; 9 | V adj; 10 | void init(int _N) { N = _N; in.rsz(N); adj.rsz(N); } 11 | void ae(int x, int y) { adj[x].pb(y), ++in[y]; } 12 | bool sort() { 13 | queue todo; 14 | F0R(i,N) if (!in[i]) todo.push(i); 15 | while (sz(todo)) { 16 | int x = todo.ft; todo.pop(); res.pb(x); 17 | each(i,adj[x]) if (!(--in[i])) todo.push(i); 18 | } 19 | return sz(res) == N; 20 | } 21 | }; 22 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Basics/TreeTour (7.2).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Subtree corresponding to \texttt{x} -> range \texttt{[st[x],en[x]]} 3 | * Source: Own 4 | */ 5 | 6 | template struct TreeTour { 7 | int st[SZ], en[SZ], par[SZ]; 8 | vi adj[SZ]; 9 | void ae(int a, int b) { adj[a].pb(b), adj[b].pb(a); } 10 | void dfs(int x) { 11 | static int t = 0; st[x] = t++; 12 | each(y,adj[x]) if (y != par[x]) { 13 | par[y] = x; dfs(y); } 14 | en[x] = t-1; 15 | } 16 | void init() { par[1] = 0; dfs(1); } 17 | }; 18 | 19 | void tourExample() { 20 | TreeTour<4> T; 21 | T.ae(1,2); T.ae(1,3); T.init(); 22 | FOR(i,1,4) ps(i,T.st[i],T.en[i]); 23 | // 1 0 2, 2 1 1, 3 2 2 24 | } 25 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/DFS/MaximalCliques.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Used only once. Finds all maximal cliques. 3 | * Time: O(3^{N/3}) 4 | * Source: KACTL 5 | * Verification: BOSPRE 2016 gaudy 6 | */ 7 | 8 | using B = bitset<128>; B adj[128]; 9 | int N; 10 | // possibly in clique, not in clique, in clique 11 | void cliques(B P = ~B(), B X={}, B R={}) { 12 | if (!P.any()) { 13 | if (!X.any()) // do smth with R 14 | return; 15 | } 16 | int q = (P|X)._Find_first(); 17 | // clique must contain q or non-neighbor of q 18 | B cands = P&~adj[q]; 19 | F0R(i,N) if (cands[i]) { 20 | R[i] = 1; cliques(P&adj[i],X&adj[i],R); 21 | R[i] = P[i] = 0; X[i] = 1; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/DFS/SCCK.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Kosaraju's Algorithm, DFS twice to generate 3 | * strongly connected components in topological order. $a,b$ 4 | * in same component if both $a\to b$ and $b\to a$ exist. 5 | * Time: O(N+M) 6 | * Source: Wikipedia 7 | * Verification: POI 8 peaceful commission 8 | */ 9 | 10 | struct SCC { 11 | int N; V adj, radj; 12 | vi todo, comp, comps; V vis; 13 | void init(int _N) { N = _N; 14 | adj.rsz(N), radj.rsz(N), comp = vi(N,-1), vis.rsz(N); } 15 | void ae(int x, int y) { adj[x].pb(y), radj[y].pb(x); } 16 | void dfs(int x) { 17 | vis[x] = 1; each(y,adj[x]) if (!vis[y]) dfs(y); 18 | todo.pb(x); } 19 | void dfs2(int x, int v) { 20 | comp[x] = v; 21 | each(y,radj[x]) if (comp[y] == -1) dfs2(y,v); } 22 | void gen() { // fills allComp 23 | F0R(i,N) if (!vis[i]) dfs(i); 24 | reverse(all(todo)); 25 | each(x,todo) if (comp[x] == -1) dfs2(x,x), comps.pb(x); 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/DFS/SCCT.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Tarjan's, DFS once to generate 3 | * strongly connected components in topological order. $a,b$ 4 | * in same component if both $a\to b$ and $b\to a$ exist. 5 | * Uses less memory than Kosaraju b/c doesn't store reverse edges. 6 | * Time: O(N+M) 7 | * Source: KACTL 8 | * https://github.com/kth-competitive-programming/kactl/blob/master/content/graph/SCC.h 9 | * Verification: https://cses.fi/problemset/task/1686/ 10 | */ 11 | 12 | struct SCC { 13 | int N, ti = 0; V adj; 14 | vi disc, comp, stk, comps; 15 | void init(int _N){ N = _N, adj.rsz(N); 16 | disc.rsz(N), comp.rsz(N,-1);} 17 | void ae(int x, int y) { adj[x].pb(y); } 18 | int dfs(int x) { 19 | int low = disc[x] = ++ti; stk.pb(x); 20 | each(y,adj[x]) if (comp[y] == -1) // comp[y] == -1, 21 | ckmin(low,disc[y]?:dfs(y)); // disc[y] != 0 -> in stack 22 | if (low == disc[x]) { // make new SCC 23 | // pop off stack until you find x 24 | comps.pb(x); for (int y = -1; y != x;) 25 | comp[y = stk.bk] = x, stk.pop_back(); 26 | } 27 | return low; 28 | } 29 | void gen() { 30 | F0R(i,N) if (!disc[i]) dfs(i); 31 | reverse(all(comps)); 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/DSU/DSU (7.6).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Disjoint Set Union with path compression 3 | * and union by size. Add edges and test connectivity. 4 | * Use for Kruskal's or Boruvka's minimum spanning tree. 5 | * Time: O(\alpha(N)) 6 | * Source: CSAcademy, KACTL 7 | * Verification: * 8 | */ 9 | 10 | struct DSU { 11 | vi e; void init(int N) { e = vi(N,-1); } 12 | int get(int x) { return e[x] < 0 ? x : e[x] = get(e[x]); } 13 | bool sameSet(int a, int b) { return get(a) == get(b); } 14 | int size(int x) { return -e[get(x)]; } 15 | bool unite(int x, int y) { // union by size 16 | x = get(x), y = get(y); if (x == y) return 0; 17 | if (e[x] > e[y]) swap(x,y); 18 | e[x] += e[y]; e[y] = x; return 1; 19 | } 20 | }; 21 | 22 | /**tcT> T kruskal(int N, vector> ed) { 23 | sort(all(ed)); 24 | T ans = 0; DSU D; D.init(N); // edges that unite are in MST 25 | each(a,ed) if (D.unite(a.s.f,a.s.s)) ans += a.f; 26 | return ans; 27 | }*/ 28 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/DSU/DSUrb (15.5).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Disjoint Set Union with Rollback 3 | * Source: see DSU 4 | * Verification: * 5 | */ 6 | 7 | struct DSUrb { 8 | vi e; void init(int n) { e = vi(n,-1); } 9 | int get(int x) { return e[x] < 0 ? x : get(e[x]); } 10 | bool sameSet(int a, int b) { return get(a) == get(b); } 11 | int size(int x) { return -e[get(x)]; } 12 | V> mod; 13 | bool unite(int x, int y) { // union-by-rank 14 | x = get(x), y = get(y); 15 | if (x == y) { mod.pb({-1,-1,-1,-1}); return 0; } 16 | if (e[x] > e[y]) swap(x,y); 17 | mod.pb({x,y,e[x],e[y]}); 18 | e[x] += e[y]; e[y] = x; return 1; 19 | } 20 | void rollback() { 21 | auto a = mod.bk; mod.pop_back(); 22 | if (a[0] != -1) e[a[0]] = a[2], e[a[1]] = a[3]; 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/DSU/DynaCon.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: offline dynamic connectivity 3 | * Source: own 4 | * Verification: https://codeforces.com/contest/1140/problem/F 5 | */ 6 | 7 | #include "DSUrb (15.5).h" 8 | 9 | template struct DynaCon { 10 | DSUrb D; vpi seg[2*SZ]; 11 | void upd(int l, int r, pi p) { // add edge p to all times in interval [l, r] 12 | for (l += SZ, r += SZ+1; l < r; l /= 2, r /= 2) { 13 | if (l&1) seg[l++].pb(p); 14 | if (r&1) seg[--r].pb(p); 15 | } 16 | } 17 | void process(int ind) { 18 | each(t,seg[ind]) D.unite(t.f,t.s); 19 | if (ind >= SZ) { 20 | // do stuff with D at time ind-SZ 21 | } else process(2*ind), process(2*ind+1); 22 | each(t,seg[ind]) D.rollback(); 23 | } 24 | }; 25 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Flows (12.3)/GlobalMinCut.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Used only once. Stoer-Wagner, find a global minimum cut in 3 | * an undirected graph as represented by an adjacency matrix. 4 | * Time: O(N^3) 5 | * Source: Stanford Notebook, http://www.cs.tau.ac.il/~zwick/grad-algo-08/gmc.pdf 6 | * https://en.wikipedia.org/wiki/Stoer%E2%80%93Wagner_algorithm 7 | * Alternatively, use https://en.wikipedia.org/wiki/Karger%27s_algorithm 8 | * Verification: https://www.spoj.com/problems/ADABANKET/ 9 | */ 10 | 11 | pair GlobalMinCut(V wei) { 12 | int N = sz(wei); 13 | vi par(N); iota(all(par),0); 14 | pair bes{INT_MAX,{}}; 15 | R0F(phase,N) { 16 | vi w = wei[0]; int lst = 0; 17 | vector add(N,1); FOR(i,1,N) if (par[i]==i) add[i]=0; 18 | F0R(i,phase) { 19 | int k = -1; 20 | FOR(j,1,N) if (!add[j] && (k==-1 || w[j]>w[k])) k = j; 21 | if (i+1 == phase) { 22 | if (w[k] < bes.f) { 23 | bes = {w[k],{}}; 24 | F0R(j,N) if (par[j] == k) bes.s.pb(j); 25 | } 26 | F0R(j,N)wei[lst][j]+=wei[k][j],wei[j][lst]=wei[lst][j]; 27 | F0R(j,N) if (par[j] == k) par[j] = lst; // merge 28 | } else { // greedily add closest 29 | F0R(j,N) w[j] += wei[k][j]; 30 | add[lst = k] = 1; 31 | } 32 | } 33 | } 34 | return bes; 35 | } -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Flows (12.3)/GomoryHu.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Returns edges of Gomory-Hu tree (second element is weight). 3 | * Max flow between pair of vertices of undirected graph is given by min edge 4 | * weight along tree path. Uses the fact that for any $i,j,k,$ 5 | * $\lambda_{ik}\ge \min(\lambda_{ij},\lambda_{jk}),$ 6 | * where $\lambda_{ij}$ denotes the flow between $i$ and $j.$ 7 | * Source: https://github.com/koosaga/DeobureoMinkyuParty/blob/master/teamnote.tex 8 | * Time: $N-1$ calls to Dinic 9 | * Verification: https://codeforces.com/problemset/problem/343/E 10 | */ 11 | 12 | #include "Dinic.h" 13 | 14 | template V> gomoryHu(int N, 15 | const V>& ed) { 16 | vi par(N); Dinic D; D.init(N); 17 | vpi ed_locs; each(t,ed)ed_locs.pb(D.ae(t.f.f,t.f.s,t.s,t.s)); 18 | V> ans; 19 | FOR(i,1,N) { 20 | each(p,ed_locs) { // reset capacities 21 | auto& e = D.adj.at(p.f).at(p.s); 22 | auto& e_rev = D.adj.at(e.to).at(e.rev); 23 | e.cap = e_rev.cap = (e.cap+e_rev.cap)/2; 24 | } 25 | ans.pb({{i,par[i]},D.maxFlow(i,par[i])}); 26 | FOR(j,i+1,N) if (par[j] == par[i] && D.lev[j]) par[j] = i; 27 | } 28 | return ans; 29 | } -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Flows (12.3)/README.md: -------------------------------------------------------------------------------- 1 | 2 | ## 5 3 | 4 | * Faster Max Flow 5 | * Hopcroft-Karp Bipartite Matching 6 | * Dinic's Algorithm 7 | * Push-Relabel 8 | * [Fast Flow Implementation - Chilli](https://codeforces.com/blog/entry/66006) 9 | * Minimum Cost Flow 10 | * Tutorial 11 | * [TopCoder](https://www.topcoder.com/community/data-science/data-science-tutorials/minimum-cost-flow-part-two-algorithms/) 12 | * [Johnson's Algorithm](https://en.wikipedia.org/wiki/Johnson%27s_algorithm) 13 | * Problems 14 | * [April Fool's Problem](http://codeforces.com/contest/802/problem/N) 15 | * [Cow & Exercise](https://codeforces.com/contest/1307/problem/G) 16 | * consider LP dual 17 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Matching/DFSmatch.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: naive bipartite matching 3 | * Time: O(NM) 4 | * Source: own 5 | * Verification: USACO Training unmatch 6 | */ 7 | 8 | template struct MaxMatch { 9 | int N, match[SZ], rmatch[SZ]; 10 | bitset vis; vi adj[SZ]; 11 | /**void connect(int a, int b, bool c = 1) { 12 | if (c) match[a] = b, rmatch[b] = a; 13 | else match[a] = rmatch[b] = 0; }*/ 14 | bool dfs(int x) { 15 | if (!x) return 1; 16 | if (vis[x]) return 0; 17 | vis[x] = 1; 18 | each(t,adj[x]) if (t != match[x] && dfs(rmatch[t])) { 19 | match[x] = t, rmatch[t] = x; return 1; } 20 | return 0; 21 | } 22 | bool tri(int x) { vis.reset(); return dfs(x); } 23 | int init(int _N) { 24 | N = _N; FOR(i,1,N+1) match[i] = rmatch[i] = 0; 25 | int res = 0; FOR(i,1,N+1) if (!match[i]) res += tri(i); 26 | return res; 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Matching/MaxMatchFast.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Fast bipartite matching. 3 | * Time: $O(M\sqrt N)$ 4 | * Source: Own 5 | * Verification: https://old.yosupo.jp/problem/bipartitenxting 6 | */ 7 | 8 | vpi maxMatch(int L, int R, const vpi& edges) { 9 | V adj = V(L); 10 | vi nxt(L,-1), prv(R,-1), lev, ptr; 11 | F0R(i,sz(edges)) adj.at(edges[i].f).pb(edges[i].s); 12 | while (true) { 13 | lev = ptr = vi(L); int max_lev = 0; 14 | queue q; F0R(i,L) if (nxt[i]==-1) lev[i]=1, q.push(i); 15 | while (sz(q)) { 16 | int x = q.ft; q.pop(); 17 | for (int y: adj[x]) { 18 | int z = prv[y]; 19 | if (z == -1) max_lev = lev[x]; 20 | else if (!lev[z]) lev[z] = lev[x]+1, q.push(z); 21 | } 22 | if (max_lev) break; 23 | } 24 | if (!max_lev) break; 25 | F0R(i,L) if (lev[i] > max_lev) lev[i] = 0; 26 | auto dfs = [&](auto self, int x) -> bool { 27 | for (;ptr[x] < sz(adj[x]);++ptr[x]) { 28 | int y = adj[x][ptr[x]], z = prv[y]; 29 | if (z == -1 || (lev[z] == lev[x]+1 && self(self,z))) 30 | return nxt[x]=y, prv[y]=x, ptr[x]=sz(adj[x]), 1; 31 | } 32 | return 0; 33 | }; 34 | F0R(i,L) if (nxt[i] == -1) dfs(dfs,i); 35 | } 36 | vpi ans; F0R(i,L) if (nxt[i] != -1) ans.pb({i,nxt[i]}); 37 | return ans; 38 | } -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Matching/MaxMatchHeuristic.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Max matching that seems to be fast (probably a counter case ...) 3 | * Time: ? 4 | * Source: https://old.yosupo.jp/submission/48179 5 | * Verification: https://old.yosupo.jp/problem/bipartitematching 6 | */ 7 | 8 | vpi maxMatch(int L, int R, const vpi& edges) { 9 | V adj(L); each(e,edges) adj[e.f].pb(e.s); 10 | vi nxt(L,-1), prv(R,-1); vb vis; 11 | for (bool flag = 1; flag;) { 12 | flag = 0; 13 | auto dfs = [&](auto self, int x) { 14 | if (vis[x]) return 0; 15 | vis[x] = 1; 16 | for (int y: adj[x]) if (prv[y] == -1) 17 | return nxt[x] = y, prv[y] = x, 1; 18 | for (int y: adj[x]) if (self(self,prv[y])) 19 | return nxt[x] = y, prv[y] = x, 1; 20 | return 0; 21 | }; 22 | vis = vb(L); 23 | F0R(i,L) if (nxt[i] == -1) flag |= dfs(dfs,i); 24 | } 25 | vpi ans; F0R(i,L) if (nxt[i] != -1) ans.eb(i,nxt[i]); 26 | return ans; 27 | } -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/README.md: -------------------------------------------------------------------------------- 1 | # 12 - Graphs (Advanced) 2 | 3 | * [DeobureoMinkyuParty ICPC Notebook](https://github.com/koosaga/DeobureoMinkyuParty/blob/master/teamnote.pdf) 4 | * Edge-Disjoint Spanning Trees 5 | * [Tarjan](http://i.stanford.edu/pub/cstr/reports/cs/tr/74/455/CS-TR-74-455.pdf) 6 | * [CF Comment](https://codeforces.com/blog/entry/68131?#comment-524705) 7 | * [CEOI Problem](https://cses.fi/file/f039dfd6ad6656f9046b68e4e32703fe211cd4df174270e0c2410a0c649a8e8e/) 8 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Trees (10)/LCAjump (10.2).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Calculates least common ancestor in tree with verts 3 | * $0\ldots N-1$ and root $R$ using binary jumping. 4 | * Time: O(N\log N) build, O(\log N) query 5 | * Memory: O(N\log N) 6 | * Source: USACO Camp, KACTL 7 | * Verification: * 8 | */ 9 | 10 | struct LCA { 11 | int N; V par, adj; vi depth; 12 | void init(int _N) { N = _N; 13 | int d = 1; while ((1<>i)&1) x = par[i][x]; 25 | return x; } 26 | int lca(int x, int y) { 27 | if (depth[x] < depth[y]) swap(x,y); 28 | x = jmp(x,depth[x]-depth[y]); if (x == y) return x; 29 | R0F(i,sz(par)) { 30 | int X = par[i][x], Y = par[i][y]; 31 | if (X != Y) x = X, y = Y; 32 | } 33 | return par[0][x]; 34 | } 35 | int dist(int x, int y) { // # edges on path 36 | return depth[x]+depth[y]-2*depth[lca(x,y)]; } 37 | }; 38 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Trees (10)/README.md: -------------------------------------------------------------------------------- 1 | # Trees 2 | 3 | ## Tree Sqrt Decomp 4 | 5 | * Mo's Algorithm 6 | * Tutorial 7 | * [CF Intro](http://codeforces.com/blog/entry/7383) 8 | * [Mo's on Trees](http://codeforces.com/blog/entry/43230) 9 | * Problems 10 | * [A2OJ](https://a2oj.com/category?ID=318) 11 | * Block Tree 12 | * Tutorial 13 | * https://codeforces.com/blog/entry/46843 14 | * Problem 15 | * https://dmoj.ca/contest/wac1 16 | * Problems 17 | * https://codeforces.com/contest/1254/problem/D 18 | * can use HLD 19 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Trees (10)/SmallToLarge (10.2).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: offline subtree queries in $O(N\log^2N)$ 3 | * Source: own 4 | * Verification: January Easy 2018 - Shubham & Tree 1 5 | */ 6 | 7 | struct SmallToLarge { 8 | int val[MX]; 9 | vi child[MX]; 10 | map dat[MX]; 11 | void comb(int a, int b) { 12 | bool swa = 0; 13 | if (sz(dat[a]) < sz(dat[b])) swap(a,b), swa = 1; 14 | // note: swapping doesn't seem to work for indexed set 15 | each(x,dat[b]) dat[a][x.f] += x.s; 16 | dat[b].clear(); 17 | if (swa) swap(dat[a],dat[b]); 18 | } 19 | void process(int ind) { 20 | dat[ind][val[ind]] ++; 21 | each(i,child[ind]) { 22 | process(i); 23 | comb(ind,i); 24 | } 25 | // now do stuff with values 26 | } 27 | }; 28 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Trees (10)/TreeDiameter (10.1).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Calculates longest path in tree. The vertex furthest 3 | * from 0 must be an endpoint of the diameter. 4 | * Source: own 5 | * Verification: 6 | * http://www.spoj.com/problems/PT07Z/ 7 | * https://codeforces.com/contest/1182/problem/D 8 | */ 9 | 10 | template struct TreeDiameter { 11 | int N, par[SZ], dist[SZ], diaLen; 12 | vi adj[SZ], dia, center; 13 | void ae(int a, int b) { adj[a].pb(b), adj[b].pb(a); } 14 | void dfs(int x) { 15 | each(y,adj[x]) if (y != par[x]) { 16 | par[y] = x; dist[y] = dist[x]+1; 17 | dfs(y); } 18 | } 19 | void genDist(int x) { par[x] = -1; dist[x] = 0; dfs(x); } 20 | void init(int _N) { 21 | N = _N; dia = {0,0}; 22 | genDist(0); F0R(i,N) if (dist[i]>dist[dia[0]]) dia[0] = i; 23 | genDist(dia[0]); F0R(i,N) if (dist[i]>dist[dia[1]]) dia[1] = i; 24 | diaLen = dist[dia[1]]; 25 | int cen = dia[1]; F0R(i,diaLen/2) cen = par[cen]; 26 | center = {cen}; if (diaLen&1) center.pb(par[cen]); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /Implementations/content/graphs (12)/Trees (10)/lcajump_old.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Calculates least common ancestor in tree 3 | * with root $R$ using binary jumping. 4 | * Time: O(N\log N) build, O(\log N) query 5 | * Memory: O(N\log N) 6 | * Source: USACO Camp 7 | * Verification: Debug the Bugs 8 | */ 9 | 10 | template struct LCA { 11 | static const int BITS = 32-__builtin_clz(SZ); 12 | int N, R = 1, par[BITS][SZ], depth[SZ]; vi adj[SZ]; 13 | void ae(int u, int v) { adj[u].pb(v), adj[v].pb(u); } 14 | /// INITIALIZE 15 | void dfs(int x, int p){ 16 | depth[x] = depth[par[0][x] = p]+1; 17 | each(y,adj[x]) if (y != p) dfs(y,x); } 18 | void init(int _N) { 19 | N = _N; dfs(R,0); 20 | FOR(k,1,BITS) FOR(i,1,N+1) 21 | par[k][i] = par[k-1][par[k-1][i]]; 22 | } 23 | /// QUERY 24 | int getPar(int a, int b) { 25 | R0F(k,BITS) if (b&(1< 2^{62} 13 | ll x,y; tie(x,y) = euclid(a.s,b.s); 14 | ll g = a.s*x+b.s*y, l = a.s/g*b.s; 15 | if ((b.f-a.f)%g) return {-1,-1}; // no solution 16 | // ?*a.s+a.f \equiv b.f \pmod{b.s} 17 | // ?=(b.f-a.f)/g*(a.s/g)^{-1} \pmod{b.s/g} 18 | x = (b.f-a.f)%b.s*x%b.s/g*a.s+a.f; 19 | return {x+(x<0)*l,l}; 20 | } 21 | -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Euclid/Euclid.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Generalized Euclidean algorithm. \texttt{euclid} and 3 | * \texttt{invGeneral} work for $A,B<2^{62}$. 4 | * Source: KACTL 5 | * Time: O(\log AB) 6 | * Verification: https://codeforces.com/gym/102411/problem/G 7 | */ 8 | 9 | // ceil(a/b) 10 | // ll cdiv(ll a, ll b) { return a/b+((a^b)>0&&a%b); } 11 | pl euclid(ll A, ll B) { // For A,B>=0, finds (x,y) s.t. 12 | // Ax+By=gcd(A,B), |Ax|,|By|<=AB/gcd(A,B) 13 | if (!B) return {1,0}; 14 | pl p = euclid(B,A%B); return {p.s,p.f-A/B*p.s}; } 15 | ll invGeneral(ll A, ll B) { // find x in [0,B) such that Ax=1 mod B 16 | pl p = euclid(A,B); assert(p.f*A+p.s*B == 1); 17 | return p.f+(p.f<0)*B; } // must have gcd(A,B)=1 -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Euclid/FracInterval.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Given fractions $a b.s) return {1+num,1}; 12 | auto x = bet({b.s,b.f},{a.s,a.f}); 13 | return {x.s+num*x.f,x.f}; 14 | } 15 | -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Euclid/modArithBrute.cpp: -------------------------------------------------------------------------------- 1 | ll minBetween_brute(ll A, ll B, ll L, ll R) { 2 | F0R(i,B) { 3 | ll prod = A*i%B; 4 | if (L <= prod && prod <= R) return i; 5 | } 6 | return -1; 7 | } 8 | 9 | ll minRemainder_brute(ll A, ll B, ll C, ll M) { 10 | ll ans = B; 11 | F0R(i,M+1) ckmin(ans,(A*i+C)%B); 12 | return ans; 13 | } 14 | 15 | int main() { 16 | setIO(); 17 | FOR(i,1,101) FOR(j,1,101) F0R(L,j) FOR(R,L,j) { 18 | ll a = minBetween(i,j,L,R); 19 | ll b = BET(i,j,L,R); 20 | if (a != b) { 21 | dbg(i,j,L,R); 22 | dbg(a); 23 | dbg(b); 24 | exit(0); 25 | } 26 | } 27 | dbg("OK"); 28 | } -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Modular Arithmetic/DiscreteLog.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: find least integer p such that r^p=x(mod MOD) 3 | * meet in the middle: O(sqrt(mod)) per query 4 | * Source: Own 5 | * Verification: https://www.hackerrank.com/contests/infinitum11/challenges/discrete-logarithm/problem 6 | */ 7 | 8 | #include "ModInt.h" 9 | 10 | struct DiscreteLog { 11 | int root, block; 12 | unordered_map u; 13 | mi cur; 14 | int query(mi x) { 15 | F0R(i,block) { 16 | if (u.count((int)x)) return i*block+u[(int)x]; 17 | x *= cur; 18 | } 19 | return -1; 20 | } 21 | void init(int r) { // gcd(m,r) = 1 22 | root = r; block = sqrt(MOD)+1; 23 | u.clear(); cur = mi(1); 24 | F0R(i,block) { 25 | if (!u.count((int)cur)) u[(int)cur] = i; 26 | cur *= root; 27 | } 28 | cur = 1/cur; 29 | } 30 | }; -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Modular Arithmetic/FastMod.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Barrett reduction computes $a \% b$ about 4 times faster than usual 3 | * where $b>1$ is constant but not known at compile time. Division by $b$ is replaced 4 | * by multiplication by $m$ and shifting right 64 bits. 5 | * Source: KACTL 6 | * https://github.com/kth-competitive-programming/kactl/blob/master/content/various/FastMod.h 7 | * https://en.wikipedia.org/wiki/Barrett_reduction 8 | * Verification: http://www.usaco.org/index.php?page=viewproblem2&cpid=1045 9 | */ 10 | 11 | using ul = uint64_t; using L = __uint128_t; 12 | struct FastMod { 13 | ul b, m; FastMod(ul b) : b(b), m(-1ULL / b) {} 14 | ul reduce(ul a) { 15 | ul q = (ul)((__uint128_t(m) * a) >> 64), r = a - q * b; 16 | return r - (r >= b) * b; } 17 | }; -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Modular Arithmetic/ModFact.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Combinations modulo a prime $MOD$. Assumes $2\le N \le MOD$. 3 | * Time: O(N) 4 | * Source: KACTL 5 | * Verification: https://dmoj.ca/problem/tle17c4p5 6 | * Usage: F.init(10); F.C(6, 4); // 15 7 | */ 8 | 9 | #include "ModInt.h" 10 | 11 | struct { 12 | vmi invs, fac, ifac; 13 | void init(int N) { // idempotent 14 | invs.rsz(N), fac.rsz(N), ifac.rsz(N); 15 | invs[1] = fac[0] = ifac[0] = 1; 16 | FOR(i,2,N) invs[i] = mi(-(ll)MOD/i*(int)invs[MOD%i]); 17 | FOR(i,1,N) fac[i] = fac[i-1]*i, ifac[i] = ifac[i-1]*invs[i]; 18 | } 19 | mi C(int a, int b) { 20 | if (a < b || b < 0) return 0; 21 | return fac[a]*ifac[b]*ifac[a-b]; 22 | } 23 | } F; -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Modular Arithmetic/ModFactInt.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: pre-compute factorial mod inverses, 3 | * assumes $MOD$ is prime and $N < MOD$. 4 | * Time: O(N) 5 | * Source: KACTL 6 | * Verification: https://dmoj.ca/problem/tle17c4p5 7 | */ 8 | 9 | #include "ModInt.h" 10 | 11 | struct Factorials { 12 | vi invs, fac, ifac; // make sure to convert to LL before doing any multiplications ... 13 | void genFac(int N) { 14 | invs.rsz(N), fac.rsz(N), ifac.rsz(N); 15 | invs[1] = fac[0] = ifac[0] = 1; 16 | FOR(i,2,N) invs[i] = int(MOD-(ll)MOD/i*invs[MOD%i]%MOD); 17 | FOR(i,1,N) { 18 | fac[i] = int((ll)fac[i-1]*i%MOD); 19 | ifac[i] = int((ll)ifac[i-1]*invs[i]%MOD); 20 | } 21 | } 22 | int C(int a, int b) { 23 | if (a < b || b < 0) return 0; 24 | return (ll)fac[a]*ifac[b]%MOD*ifac[a-b]%MOD; 25 | } 26 | }; 27 | -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Modular Arithmetic/ModIntShort.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Modular arithmetic. Assumes $MOD$ is prime. 3 | * Source: KACTL 4 | * Verification: https://open.kattis.com/problems/modulararithmetic 5 | * Usage: mi a = MOD+5; inv(a); // 400000003 6 | */ 7 | 8 | template struct mint { 9 | static const int mod = MOD; 10 | static constexpr mint rt() { return RT; } // primitive root 11 | int v; 12 | explicit operator int() const { return v; } 13 | mint():v(0) {} 14 | mint(ll _v):v(int(_v%MOD)) { v += (v<0)*MOD; } 15 | mint& operator+=(mint o) { 16 | if ((v += o.v) >= MOD) v -= MOD; 17 | return *this; } 18 | mint& operator-=(mint o) { 19 | if ((v -= o.v) < 0) v += MOD; 20 | return *this; } 21 | mint& operator*=(mint o) { 22 | v = int((ll)v*o.v%MOD); return *this; } 23 | friend mint pow(mint a, ll p) { assert(p >= 0); 24 | return p==0?1:pow(a*a,p/2)*(p&1?a:1); } 25 | friend mint inv(mint a) { assert(a.v != 0); return pow(a,MOD-2); } 26 | friend mint operator+(mint a, mint b) { return a += b; } 27 | friend mint operator-(mint a, mint b) { return a -= b; } 28 | friend mint operator*(mint a, mint b) { return a *= b; } 29 | }; 30 | using mi = mint<(int)1e9+7, 5>; 31 | using vmi = V; -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Modular Arithmetic/ModIntShort_Old.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Modular arithmetic. Assumes $MOD$ is prime. 3 | * Source: KACTL 4 | * Verification: https://open.kattis.com/problems/modulararithmetic 5 | * Usage: mi a = MOD+5; inv(a); // 400000003 6 | */ 7 | 8 | struct mi { 9 | int v; /// explicit operator int() const { return v; } 10 | mi():v(0) {} 11 | mi(ll _v):v(int(_v%MOD)) { v += (v<0)*MOD; } 12 | }; 13 | using vmi = V; 14 | mi& operator+=(mi& a, mi b) { 15 | if ((a.v += b.v) >= MOD) a.v -= MOD; 16 | return a; } 17 | mi& operator-=(mi& a, mi b) { 18 | if ((a.v -= b.v) < 0) a.v += MOD; 19 | return a; } 20 | mi operator+(mi a, mi b) { return a += b; } 21 | mi operator-(mi a, mi b) { return a -= b; } 22 | mi operator*(mi a, mi b) { return mi((ll)a.v*b.v); } 23 | mi& operator*=(mi& a, mi b) { return a = a*b; } 24 | mi pow(mi a, ll p) { assert(p >= 0); // won't work for negative p 25 | return p==0?1:pow(a*a,p/2)*(p&1?a:1); } 26 | mi inv(mi a) { assert(a.v != 0); return pow(a,MOD-2); } 27 | mi operator/(mi a, mi b) { return a*inv(b); } -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Modular Arithmetic/ModMulLL.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Multiply two 64-bit integers mod another if 128-bit is not available. 3 | * modMul is equivalent to \texttt{(ul)(\_\_int128(a)*b\%mod)}. 4 | * Works for $0\le a,b=(ll)mod))*mod; } 15 | ul modMul(ul a, ul b, const ul mod){ 16 | return __int128(a) * __int128(b) % mod; 17 | } 18 | ul modPow(ul a, ul b, const ul mod) { 19 | if (b == 0) return 1; 20 | ul res = modPow(a,b/2,mod); res = modMul(res,res,mod); 21 | return b&1 ? modMul(res,a,mod) : res; 22 | } 23 | -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Modular Arithmetic/ModSqrt.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Tonelli-Shanks algorithm for square roots mod a prime. -1 if doesn't exist. 3 | * Time: O(\log^2(MOD)) 4 | * Source: http://www.math.vt.edu/people/brown/class_homepages/shanks_tonelli.pdf 5 | * Verification: https://www.spoj.com/problems/CRYPTO1 6 | * Usage: sqrt(mi((ll)1e10)); // 100000 7 | */ 8 | 9 | #include "ModInt.h" 10 | 11 | using T = int; 12 | T sqrt(mi a) { 13 | mi p = pow(a,(MOD-1)/2); 14 | if (p.v != 1) return p.v == 0 ? 0 : -1; 15 | /// check if 0 or no sqrt 16 | T s = MOD-1; int r = 0; while (s%2 == 0) s /= 2, ++r; 17 | mi n = 2; while (pow(n,(MOD-1)/2).v == 1) n = T(n)+1; 18 | // n non-square, ord(g)=2^r, ord(b)=2^m, ord(g)=2^r, m ord(g) = 2^{m+1} 4 | * if x'=x*g, then b' = b*g^2 5 | (b')^{2^{m-1}} = (b*g^2)^{2^{m-1}} 6 | = b^{2^{m-1}}*g^{2^m} 7 | = -1*-1 8 | = 1 9 | -> ord(b')|ord(b)/2 10 | * m decreases by at least one each iteration 11 | */ -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Modular Arithmetic/Order.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Calculates smallest P such that x^P equiv 1 (mod p) 3 | * Source: Own 4 | * Verification: https://atcoder.jp/contests/jag2015summer-day4/tasks/icpc2015summer_day4_d 5 | */ 6 | 7 | #include "ModMulLL.h" 8 | #include "../Primality/FactorBasic.h" 9 | 10 | ll order(ll x, ll p) { 11 | if (gcd(x,p) != 1) return 0; 12 | ll P = phi(p); auto a = factor(P); 13 | each(t,a) while (P % t.f == 0 14 | && modPow(x,P/t.f,p) == 1) P /= t.f; 15 | return P; 16 | } 17 | -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Primality/FactorBasic.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Factors integers. 3 | * Time: O(\sqrt N) 4 | * Source: Own 5 | * Verification: https://csacademy.com/contest/ceoi-2018-day-2/task/toys-big/ 6 | */ 7 | 8 | inline namespace factorBasic { 9 | template vector> factor(T x) { 10 | vector> pri; 11 | for (T i = 2; i*i <= x; ++i) if (x % i == 0) { 12 | int t = 0; 13 | while (x % i == 0) x /= i, t ++; 14 | pri.pb({i,t}); 15 | } 16 | if (x > 1) pri.pb({x,1}); 17 | return pri; 18 | } 19 | /* Note: 20 | * number of operations needed s.t. 21 | * phi(phi(...phi(n)...))=1 22 | * is O(log n). 23 | * Euler's theorem: a^{\phi(p)}\equiv 1 (mod p), gcd(a,p)=1 24 | */ 25 | ll phi(ll x) { 26 | each(a,factor(x)) x -= x/a.f; 27 | return x; 28 | } 29 | template void tour(vector>& v, 30 | vector& V, int ind, T cur) { 31 | if (ind == sz(v)) V.pb(cur); 32 | else { 33 | T mul = 1; 34 | F0R(i,v[ind].s+1) { 35 | tour(v,V,ind+1,cur*mul); 36 | mul *= v[ind].f; 37 | } 38 | } 39 | } 40 | template vector getDivi(T x) { 41 | auto v = factor(x); 42 | vector V; tour(v,V,0,(T)1); sort(all(V)); 43 | return V; 44 | } 45 | } -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Primality/FactorFast.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Pollard-rho randomized factorization algorithm. Returns prime 3 | * factors of a number, in arbitrary order (e.g. 2299 -> \{11, 19, 11\}). 4 | * Time: $O(N^{1/4})$, less for numbers with small factors 5 | * Source: KACTL 6 | * https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm 7 | * https://codeforces.com/contest/1033/submission/44009089 is faster? 8 | * Verification: https://www.spoj.com/problems/FACT0/ 9 | */ 10 | 11 | #include "MillerRabin.h" 12 | #include "../Modular Arithmetic/ModMulLL.h" 13 | 14 | ul pollard(ul n) { // return some nontrivial factor of n 15 | auto f = [n](ul x) { return modMul(x, x, n) + 1; }; 16 | ul x = 0, y = 0, t = 30, prd = 2, i = 1, q; 17 | while (t++ % 40 || gcd(prd, n) == 1) { /// speedup: don't take gcd every it 18 | if (x == y) x = ++i, y = f(x); 19 | if ((q = modMul(prd, max(x,y)-min(x,y), n))) prd = q; 20 | x = f(x), y = f(f(y)); 21 | } 22 | return gcd(prd, n); 23 | } 24 | void factor_rec(ul n, map& cnt) { 25 | if (n == 1) return; 26 | if (prime(n)) { ++cnt[n]; return; } 27 | ul u = pollard(n); 28 | factor_rec(u,cnt), factor_rec(n/u,cnt); 29 | } 30 | 31 | /// V> factor(ul n) { 32 | /// map cnt; factor_rec(n,cnt); 33 | /// return V>(all(cnt)); 34 | /// } -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Primality/MillerRabin.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Deterministic primality test, works up to $2^{64}$. 3 | * For larger numbers, extend $A$ randomly. 4 | * Source: KACTL 5 | * https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test 6 | * Verification: https://www.spoj.com/problems/FACT0/ 7 | */ 8 | 9 | #include "ModMulLL.h" 10 | 11 | bool prime(ul n) { // not ll! 12 | if (n < 2 || n % 6 % 4 != 1) return n-2 < 2; 13 | ul A[] = {2, 325, 9375, 28178, 450775, 9780504, 1795265022}, 14 | s = __builtin_ctzll(n-1), d = n>>s; 15 | each(a,A) { // ^ count trailing zeroes 16 | ul p = modPow(a,d,n), i = s; 17 | while (p != 1 && p != n-1 && a%n && i--) p = modMul(p,p,n); 18 | if (p != n-1 && i != s) return 0; 19 | } 20 | return 1; 21 | } -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Primality/MultiplicativePrefixSums.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: $\sum_{i=1}^Nf(i)$ where $f(i)=\prod \texttt{val}[e]$ for each $p^e$ 3 | * in the factorization of $i$. Must satisfy $\texttt{val}[1]=1$. 4 | * Generalizes to any multiplicative function with $f(p)=p^{\text{fixed power}}$. 5 | * Time: $O(\sqrt N)$ 6 | * Source: Project Euler, https://oeis.org/A085731 7 | * Verification: https://www.codechef.com/problems/TABRARRAY 8 | */ 9 | 10 | #include "Sieve.h" 11 | 12 | vmi val; 13 | mi get_prefix(ll N, int p = 0) { 14 | mi ans = N; 15 | for (; S.primes.at(p) <= N / S.primes.at(p); ++p) { 16 | ll new_N = N / S.primes.at(p) / S.primes.at(p); 17 | for (int idx = 2; new_N; ++idx, new_N /= S.primes.at(p)) { 18 | ans += (val.at(idx) - val.at(idx - 1)) 19 | * get_prefix(new_N, p + 1); 20 | } 21 | } 22 | return ans; 23 | } -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Primality/MultiplicativePrefix_Old.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: $\sum_{i=1}^Nf(i)$ for any multiplicative function 3 | * $f$ such that for square-free $x$, $f(x) = x^e$ for some fixed $e$ 4 | * Usage: $pre0(N, 0)$ or $pre1(N, 0)$ 5 | * Time: $O(\sqrt N)$ 6 | * Source: Project Euler, https://oeis.org/A085731 7 | * Verification: https://www.codechef.com/problems/TABRARRAY 8 | */ 9 | 10 | #include "Sieve.h" 11 | 12 | ll pre0(ll n, int i) { // prod(primes) in factorization of x 13 | ll res = n*(n+1)/2; // assume all square-free 14 | for (;;++i) { 15 | ll p = S.pr[i], nn = n/p/p; if (!nn) break; 16 | for(ll coef=p*(p-1);nn;nn/=p)res-=coef*pre0(nn,i+1); 17 | } 18 | return res; 19 | } 20 | ll pre1(ll n, int i) { // gcd of x and arithmetic derivative 21 | // p^e contributes p^e if e%p == 0 and p^{e-1} otherwise 22 | ll res = n; // assume all square-free 23 | for (;;++i) { 24 | ll p = S.pr[i], nn = n/p/p; if (!nn) break; 25 | ll lst = 1, mul = p*p; 26 | for (int e = 2; nn; mul *= p, nn /= p, ++e) { 27 | ll nex = mul; if (e%p) nex /= p; 28 | if (lst != nex) res += (nex-lst)*pre1(nn,i+1); 29 | lst = nex; 30 | } 31 | } 32 | return res; 33 | } -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Primality/PrimeCnt.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Counts number of primes up to $N$. Can also count 3 | * sum of primes. 4 | * Time: $O(N^{3/4}/\log N)$, ~60ms for $N=10^{11}$, ~2.5s for $N=10^{13}$ 5 | * Source: https://old.yosupo.jp/submission/7976 6 | * Verification: https://old.yosupo.jp/problem/counting_primes 7 | */ 8 | 9 | ll count_primes(ll N) { // count_primes(1e13) == 346065536839 10 | if (N <= 1) return 0; 11 | int sq = (int)sqrt(N); 12 | vl big_ans((sq+1)/2), small_ans(sq+1); 13 | FOR(i,1,sq+1) small_ans[i] = (i-1)/2; 14 | F0R(i,sz(big_ans)) big_ans[i] = (N/(2*i+1)-1)/2; 15 | vb skip(sq+1); int prime_cnt = 0; 16 | for (int p = 3; p <= sq; p += 2) if (!skip[p]) { // primes 17 | for (int j = p; j <= sq; j += 2*p) skip[j] = 1; 18 | F0R(j,min((ll)sz(big_ans),(N/p/p+1)/2)) { 19 | ll prod = (ll)(2*j+1)*p; 20 | big_ans[j] -= (prod > sq ? small_ans[(double)N/prod] 21 | : big_ans[prod/2])-prime_cnt; 22 | } 23 | for (int j = sq, q = sq/p; q >= p; --q) for (;j >= q*p;--j) 24 | small_ans[j] -= small_ans[q]-prime_cnt; 25 | ++prime_cnt; 26 | } 27 | return big_ans[0]+1; 28 | } -------------------------------------------------------------------------------- /Implementations/content/number-theory (11.1)/Primality/Sieve.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Tests primality up to $SZ$. Runs faster if only 3 | * odd indices are stored. 4 | * Time: O(SZ\log\log SZ) or O(SZ) 5 | * Source: KACTL 6 | * Verification: https://open.kattis.com/problems/primesieve 7 | */ 8 | 9 | template struct Sieve { 10 | bitset is_prime; vi primes; 11 | Sieve() { 12 | is_prime.set(); is_prime[0] = is_prime[1] = 0; 13 | for (int i = 4; i < SZ; i += 2) is_prime[i] = 0; 14 | for (int i = 3; i*i < SZ; i += 2) if (is_prime[i]) 15 | for (int j = i*i; j < SZ; j += i*2) is_prime[j] = 0; 16 | F0R(i,SZ) if (is_prime[i]) primes.pb(i); 17 | } 18 | // int sp[SZ]{}; // smallest prime that divides 19 | // Sieve() { // above is faster 20 | // FOR(i,2,SZ) { 21 | // if (sp[i] == 0) sp[i] = i, primes.pb(i); 22 | // for (int p: primes) { 23 | // if (p > sp[i] || i*p >= SZ) break; 24 | // sp[i*p] = p; 25 | // } 26 | // } 27 | // } 28 | }; -------------------------------------------------------------------------------- /Implementations/content/numerical/Matrix (11.3)/MatrixTree.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Kirchhoff's Matrix Tree Theorem. 3 | * Given adjacency matrix, calculates \# of spanning trees. 4 | * Source: various 5 | * Verification: TC Finals 2022 1000 6 | */ 7 | 8 | #include "MatrixInv.h" 9 | 10 | T numSpan(const Mat& m) { 11 | int n = sz(m); Mat res = makeMat(n-1,n-1); 12 | F0R(i,n) FOR(j,i+1,n) { 13 | mi ed = m[i][j]; res[i][i] += ed; 14 | if (j != n-1) { 15 | res[j][j] += ed; 16 | res[i][j] -= ed, res[j][i] -= ed; 17 | } 18 | } 19 | return gauss(res).f; 20 | } -------------------------------------------------------------------------------- /Implementations/content/numerical/Matrix (11.3)/ShermanMorrison.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Calculates $(A+uv^T)^{-1}$ given $B=A^{-1}$. 3 | * Not invertible if \texttt{sum=0}. 4 | * Source: https://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula 5 | * Verification: F from https://codeforces.com/gym/101981 6 | */ 7 | 8 | #include "MatrixInv.h" 9 | 10 | void ad(Mat& B, const V& u, const V& v) { 11 | int n = sz(A); V x(n), y(n); 12 | F0R(i,n) F0R(j,n) 13 | x[i] += B[i][j]*u[j], y[j] += v[i]*B[i][j]; 14 | T sum = 1; F0R(i,n) F0R(j,n) sum += v[i]*B[i][j]*u[j]; 15 | F0R(i,n) F0R(j,n) B[i][j] -= x[i]*y[j]/sum; 16 | } -------------------------------------------------------------------------------- /Implementations/content/numerical/Matrix (11.3)/SparseDet.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Tries to find characteristic equation of matrix -> determinant. 3 | * Source: 4 | * https://github.com/yosupo06/library-checker-problems/blob/a14bd2360b01cac091efa8cc62cee0a9b65ae775/math/sparse_matrix_det/sol/correct.cpp 5 | * https://mathworld.wolfram.com/CharacteristicEquation.html 6 | * https://codeforces.com/blog/entry/76945?#comment-638126 7 | * Verification: https://judge.yosupo.jp/problem/sparse_matrix_det 8 | */ 9 | 10 | #include "LinRec.h" 11 | 12 | mi sparseDet(int N, V> A) { // nonzero entries of matrix, no repeats 13 | auto gen = []() { return rng()%(MOD-1)+1; }; 14 | vmi l(N), r(N), seq(2*N); F0R(i,N) l[i] = gen(), r[i] = gen(); 15 | F0R(i,2*N) { // consider l*A^i*r, recurrence satisfies characteristic equation 16 | F0R(j,N) seq[i] += l[j]*r[j]; 17 | vmi R(N); each(t,A) R[t.f.s] += r[t.f.f]*t.s; 18 | swap(r,R); 19 | } 20 | LinRec L; L.init(seq); // hopefully found characteristic equation 21 | if (L.C.bk == 0) return 0; // 0 is root of characteristic equation 22 | if (sz(L.C) != N) return sparseDet(N,ed); // keep trying ... 23 | mi res = L.C.bk; if (!(N&1)) res *= -1; 24 | return res; 25 | }; 26 | -------------------------------------------------------------------------------- /Implementations/content/numerical/Matrix (11.3)/XorBasis.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: XOR basis. If \texttt{x} is in basis \texttt{b} 3 | * then returns 0, otherwise returns adds it to 1. Equivalent 4 | * to Gaussian Elimination. 5 | * Source: Own 6 | * Verification: GP of Nanjing 2020 A 7 | * https://atcoder.jp/contests/agc045/tasks/agc045_a (first solve :D) 8 | */ 9 | 10 | ll red(vl& b, ll x) { each(t,b) ckmin(x,x^t); 11 | return x; } 12 | bool add(vl& b, ll x) { 13 | if (!(x = red(b,x))) return 0; 14 | int ind=0; while (indx) ind ++; 15 | b.insert(begin(b)+ind,x); return 1; 16 | } 17 | 18 | /** 19 | ps(add(a,1)); // true 20 | ps(add(a,2)); // true 21 | ps(add(a,3)); // false 22 | ps(add(a,7)); // true 23 | ps(add(a,4)); // false 24 | */ 25 | -------------------------------------------------------------------------------- /Implementations/content/numerical/Misc/GoldenSectionSearch.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Finds the argument minimizing the function $f$ in the interval $[a,b]$ assuming 3 | * $f$ is unimodal on the interval, i.e. has only one local minimum. The maximum error in the 4 | * result is $eps$. Works equally well for maximization with a small change in the code. 5 | * Source: https://github.com/kth-competitive-programming/kactl/blob/master/content/numerical/GoldenSectionSearch.h 6 | * Verification: https://codeforces.com/contest/1427/problem/H 7 | * Usage: gss(-1000,1000,[](db x) { return 4+x+.3*x*x; }); // -5/3 8 | * Time: O(\log((b-a) / \epsilon)) 9 | */ 10 | 11 | /// It is important for r to be precise, otherwise we don't necessarily maintain the inequality a < x1 < x2 < b. 12 | db gss(db a, db b, function f) { 13 | db r = (sqrt(5)-1)/2, eps = 1e-7; 14 | db x1 = b - r*(b-a), x2 = a + r*(b-a); 15 | db f1 = f(x1), f2 = f(x2); 16 | while (b-a > eps) 17 | if (f1 < f2) { // change to > to find maximum 18 | b = x2; x2 = x1; f2 = f1; 19 | x1 = b - r*(b-a); f1 = f(x1); 20 | } else { 21 | a = x1; x1 = x2; f1 = f2; 22 | x2 = a + r*(b-a); f2 = f(x2); 23 | } 24 | return a; 25 | } -------------------------------------------------------------------------------- /Implementations/content/numerical/Misc/Integrate.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Integration of a function over an interval using 3 | * Simpson's rule, exact for polynomials of degree up to 3. 4 | * The error should be proportional to $dif^4$, although in 5 | * practice you will want to verify that the result is stable to desired 6 | * precision when epsilon changes. 7 | * Source: KACTL 8 | * https://en.wikipedia.org/wiki/Simpson%27s_rule 9 | * Verification: https://codeforces.com/gym/101793/problem/C 10 | * Usage: quad([](db x) { return x*x+3*x+1; }, 2, 3) // 14.833... 11 | */ 12 | 13 | template db quad(F f, db a, db b) { 14 | const int n = 1000; 15 | db dif = (b-a)/2/n, tot = f(a)+f(b); 16 | FOR(i,1,2*n) tot += f(a+i*dif)*(i&1?4:2); 17 | return tot*dif/3; 18 | } -------------------------------------------------------------------------------- /Implementations/content/numerical/Misc/IntegrateAdaptive.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Unused. Fast integration using adaptive Simpson's rule, 3 | * exact for polynomials of degree up to 5. 4 | * Source: KACTL 5 | * https://en.wikipedia.org/wiki/Adaptive_Simpson%27s_method 6 | * Verification: ? 7 | * Usage: 8 | db z, y; 9 | db h(db x) { return x*x + y*y + z*z <= 1; } 10 | db g(db y) { ::y = y; return quad(h, -1, 1); } 11 | db f(db z) { ::z = z; return quad(g, -1, 1); } 12 | db sphereVol = quad(f,-1,1), pi = sphereVol*3/4; 13 | */ 14 | 15 | template db simpson(F f, db a, db b) { 16 | db c = (a+b)/2; return (f(a)+4*f(c)+f(b))*(b-a)/6; } 17 | template db rec(F& f, db a, db b, db eps, db S) { 18 | db c = (a+b)/2; 19 | db S1 = simpson(f,a,c), S2 = simpson(f,c,b), T = S1+S2; 20 | if (abs(T-S)<=15*eps || b-a<1e-10) return T+(T-S)/15; 21 | return rec(f,a,c,eps/2,S1)+rec(f,c,b,eps/2,S2); 22 | } 23 | template db quad(F f, db a, db b, db eps = 1e-8) { 24 | return rec(f,a,b,eps,simpson(f,a,b)); } -------------------------------------------------------------------------------- /Implementations/content/numerical/Polynomials/ChirpZ.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Modified Chirp-Z. For $x\neq 0$, computes 3 | * $A(x^0), A(x^1), \ldots, A(x^{n-1})$. 4 | * Time: FFT(2|A|+n) 5 | * Source: https://cp-algorithms.com/algebra/polynomial.html 6 | * https://github.com/e-maxx-eng/e-maxx-eng-aux/blob/master/src/polynomial.cpp 7 | * https://codeforces.com/blog/entry/82165 8 | * Verification: 9 | * https://codeforces.com/contest/1054/problem/H 10 | */ 11 | 12 | #include "FFT.h" 13 | 14 | poly chirpz(poly A, T x, int n) { 15 | auto gen = [&](T c) -> poly { 16 | poly p(sz(A)+n); p[0] = 1; 17 | T t = 1; FOR(i,1,sz(p)) p[i] = p[i-1]*t, t *= c; 18 | return p; 19 | }; // uses ij = -C(i,2)+C(i+j,2)-C(j,2) 20 | poly ip = gen(1/x); F0R(i,sz(A)) A[i] *= ip[i]; 21 | reverse(all(A)); poly res = mul(A,gen(x)); 22 | res = poly(sz(A)-1+all(res)); F0R(i,n) res[i] *= ip[i]; 23 | return res; 24 | } 25 | // poly chirpzNaive(poly A, T x, int n) { 26 | // poly res; F0R(i,n) res.pb(eval(A,pow(x,i))); 27 | // return res; } -------------------------------------------------------------------------------- /Implementations/content/numerical/Polynomials/PolyConv.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Multiply small polys directly, otherwise use FFT. 3 | * Source: KACTL, https://cp-algorithms.com/algebra/fft.html 4 | */ 5 | 6 | #include "Poly.h" 7 | #include "FFT.h" 8 | 9 | bool small(const poly& a, const poly& b) { // multiply directly 10 | return min(sz(a),sz(b)) <= 60; } 11 | // vmi smart(const vmi& a, const vmi& b) { return mul(a,b); } 12 | // vl smart(const vl& a, const vl& b) { 13 | // auto X = mul(vcd(all(a)),vcd(all(b))); 14 | // vl x(sz(X)); F0R(i,sz(X)) x[i] = round(X[i].real()); 15 | // return x; } 16 | poly conv(const poly& a, const poly& b) { 17 | return small(a,b) ? a*b : mul(a,b); } -------------------------------------------------------------------------------- /Implementations/content/numerical/Polynomials/PolyInterpolate.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: $n$ points determine unique polynomial of degree $\le n-1$. 3 | * For numerical precision pick $v[k].f = c*\cos(k/(n-1)*\pi), k=0 \dots n-1$. 4 | * Time: O(n^2) 5 | * Source: KACTL 6 | * Verification: see FFT 7 | */ 8 | 9 | #include "Poly.h" 10 | 11 | poly interpolate(V> v) { 12 | poly res, tmp{1}; 13 | F0R(i,sz(v)) { T prod = 1; // add one point at a time 14 | F0R(j,i) v[i].s -= prod*v[j].s, prod *= v[i].f-v[j].f; 15 | v[i].s /= prod; res += v[i].s*tmp; tmp *= poly{-v[i].f,1}; 16 | } // add multiple of (x-v[0].f)*(x-v[1].f)*...*(x-v[i-1].f) 17 | return res; 18 | } 19 | /** 20 | poly _interpolate(vector> v) { 21 | poly ret, prod = {1}; each(t,v) prod *= poly({-t.f,1}); 22 | F0R(i,sz(v)) { 23 | T fac = 1; F0R(j,sz(v)) if (i != j) fac *= v[i].f-v[j].f; 24 | ret += v[i].s/fac*quoRem(prod,{-v[i].f,1}).f; 25 | } 26 | return ret; 27 | } 28 | 29 | vector> v; poly p = {4,6,7,11}, x = {1,3,9,16}; 30 | each(X,x) v.pb({X,eval(p,X)}); 31 | ps(interpolate(v)); 32 | */ 33 | -------------------------------------------------------------------------------- /Implementations/content/numerical/Polynomials/PolyRoots.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Source: KACTL 3 | * Description: Finds the real roots of a polynomial. 4 | * Usage: poly_roots({{2,-3,1}},-1e9,1e9) // solve x^2-3x+2 = 0 5 | * Time: O(N^2 \log(1/\epsilon)) 6 | * Verification: https://open.kattis.com/problems/firingphaser 7 | */ 8 | 9 | #include "Poly.h" 10 | 11 | typedef db T; 12 | poly polyRoots(poly p, T xmin, T xmax) { 13 | if (sz(p) == 2) { return {-p[0]/p[1]}; } 14 | auto dr = polyRoots(dif(p),xmin,xmax); 15 | dr.pb(xmin-1); dr.pb(xmax+1); sort(all(dr)); 16 | poly ret; 17 | F0R(i,sz(dr)-1) { 18 | T l = dr[i], h = dr[i+1]; 19 | bool sign = eval(p,l) > 0; 20 | if (sign^(eval(p,h) > 0)) { 21 | F0R(it,60) { // while (h-l > 1e-8) 22 | auto m = (l+h)/2, f = eval(p,m); 23 | if ((f <= 0) ^ sign) l = m; 24 | else h = m; 25 | } 26 | ret.pb((l+h)/2); 27 | } 28 | } 29 | return ret; 30 | } 31 | -------------------------------------------------------------------------------- /Implementations/content/numerical/chapter.tex: -------------------------------------------------------------------------------- 1 | \chapter{Numerical} 2 | 3 | \section{Matrix} 4 | \kactlimport{Matrix (11.3)/Matrix.h} 5 | \kactlimport{Matrix (11.3)/MatrixInv.h} 6 | \kactlimport{Matrix (11.3)/MatrixTree.h} 7 | \kactlimport{Matrix (11.3)/ShermanMorrison.h} 8 | 9 | \section{Polynomials} 10 | % \kactlimport{Polynomials/Karatsuba.h} 11 | \kactlimport{Polynomials/Poly.h} 12 | \kactlimport{Polynomials/PolyInterpolate.h} 13 | % \kactlimport{Polynomials/PolyRoots.h} 14 | \kactlimport{Polynomials/FFT.h} 15 | % \kactlimport{Polynomials/PolyConv.h} 16 | \kactlimport{Polynomials/PolyInvSimpler.h} 17 | 18 | \section{Misc} 19 | \kactlimport{Misc/LinearRecurrence.h} 20 | \kactlimport{Misc/Integrate.h} 21 | \kactlimport{Misc/IntegrateAdaptive.h} 22 | \kactlimport{Misc/Simplex.h} -------------------------------------------------------------------------------- /Implementations/content/strings (14)/Heavy/paltree_old.h: -------------------------------------------------------------------------------- 1 | // simpler version, solves APIO palindrome 2 | 3 | template struct palTree { 4 | static const int sigma = 26; 5 | int s[SZ], len[SZ], link[SZ], to[SZ][sigma], oc[SZ]; 6 | int n, last, sz; 7 | palTree() { 8 | s[n++] = -1; 9 | link[0] = 1; 10 | len[1] = -1; 11 | sz = 2; 12 | } 13 | int get_link(int v) { 14 | while(s[n-len[v]-2] != s[n-1]) v = link[v]; 15 | return v; 16 | } 17 | void add_letter(int c) { 18 | s[n++] = c; 19 | last = get_link(last); 20 | if (!to[last][c]) { 21 | len[sz] = len[last]+2; 22 | link[sz] = to[get_link(link[last])][c]; 23 | to[last][c] = sz++; 24 | } 25 | last = to[last][c]; 26 | oc[last] ++; 27 | } 28 | void prop() { 29 | vpi v; 30 | FOR(i,2,sz) v.pb({len[i],i}); 31 | sort(all(v)); reverse(all(v)); 32 | for (auto a: v) oc[link[a.s]] += oc[a.s]; 33 | } 34 | }; -------------------------------------------------------------------------------- /Implementations/content/strings (14)/Light/AhoCorasickFixed.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Aho-Corasick for fixed alphabet. For each prefix, 3 | * stores link to max length suffix which is also a prefix. 4 | * Time: O(N\sum) 5 | * Source: https://ideone.com/0cMjZJ 6 | * https://codeforces.com/contest/710/problem/F 7 | * https://codeforces.com/contest/1207/problem/G 8 | */ 9 | 10 | template struct ACfixed { 11 | struct Node { AR to; int link; }; 12 | V d{{}}; 13 | int add(str s) { // add word 14 | int v = 0; 15 | each(C,s) { 16 | int c = C-'a'; 17 | if (!d[v].to[c]) d[v].to[c] = sz(d), d.eb(); 18 | v = d[v].to[c]; 19 | } 20 | return v; 21 | } 22 | void init() { // generate links 23 | d[0].link = -1; 24 | queue q; q.push(0); 25 | while (sz(q)) { 26 | int v = q.ft; q.pop(); 27 | F0R(c,ASZ) { 28 | int u = d[v].to[c]; if (!u) continue; 29 | d[u].link = d[v].link == -1 ? 0 : d[d[v].link].to[c]; 30 | q.push(u); 31 | } 32 | if (v) F0R(c,ASZ) if (!d[v].to[c]) 33 | d[v].to[c] = d[d[v].link].to[c]; 34 | } 35 | } 36 | }; 37 | -------------------------------------------------------------------------------- /Implementations/content/strings (14)/Light/AhoCorasickUnfixed.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: for each prefix, stores link to max length suffix which is also a prefix 3 | * Source: https://ideone.com/0cMjZJ 4 | * Verification: 5 | * Kattis stringmultimatching 6 | */ 7 | 8 | struct ACunfixed { 9 | struct node { 10 | map to; 11 | int link; 12 | }; 13 | V d; 14 | ACunfixed() { d.eb(); } 15 | int add(str s) { // add word 16 | int v = 0; 17 | each(c,s) { 18 | if (!d[v].to.count(c)) { 19 | d[v].to[c] = sz(d); 20 | d.eb(); 21 | } 22 | v = d[v].to[c]; 23 | } 24 | return v; 25 | } 26 | int nex(int j, char c) { // state after adding character 27 | while (j != -1 && !d[j].to.count(c)) j = d[j].link; 28 | return j == -1 ? 0 : d[j].to[c]; 29 | } 30 | void init() { // generate links 31 | d[0].link = -1; 32 | queue q; q.push(0); 33 | while (sz(q)) { 34 | int v = q.ft; q.pop(); 35 | each(it,d[v].to) { 36 | int u = it.s; d[u].link = nex(d[v].link,it.f); 37 | q.push(u); 38 | } 39 | } 40 | } 41 | }; 42 | -------------------------------------------------------------------------------- /Implementations/content/strings (14)/Light/KMP.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Source: KACTL 3 | * Time: O(N) 4 | * Description: \texttt{f[i]} is length of the longest proper suffix 5 | * of the $i$-th prefix of $s$ that is a prefix of $s$ 6 | * Verification: https://open.kattis.com/problems/stringmatching 7 | */ 8 | 9 | vi kmp(str s) { 10 | int N = sz(s); vi f(N+1); f[0] = -1; 11 | FOR(i,1,N+1) { 12 | for (f[i]=f[i-1];f[i]!=-1&&s[f[i]]!=s[i-1];)f[i]=f[f[i]]; 13 | ++f[i]; } 14 | return f; 15 | } 16 | vi getOc(str a, str b) { // find occurrences of a in b 17 | vi f = kmp(a+"@"+b), ret; 18 | FOR(i,sz(a),sz(b)+1) if (f[i+sz(a)+1] == sz(a)) 19 | ret.pb(i-sz(a)); 20 | return ret; 21 | } 22 | -------------------------------------------------------------------------------- /Implementations/content/strings (14)/Light/LyndonFactor.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: 3 | * A string is "simple" if it is strictly smaller than any of its own nontrivial suffixes. 4 | * The Lyndon factorization of the string $s$ is a factorization $s=w_1w_2\ldots w_k$ 5 | * where all strings $w_i$ are simple and $w_1\ge w_2\ge \cdots \ge w_k.$ Min rotation 6 | * gets min index i such that cyclic shift of s starting at i is minimum. 7 | * Source: https://cp-algorithms.com/string/lyndon_factorization.html 8 | * Time: O(N) 9 | * Verification: https://uva.onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=660 10 | */ 11 | 12 | vs duval(str s) { 13 | int N = sz(s); vs factors; 14 | for (int i = 0; i < N; ) { 15 | int j = i+1, k = i; 16 | for (; j < N && s[k] <= s[j]; ++j) { 17 | if (s[k] < s[j]) k = i; 18 | else ++k; 19 | } 20 | for (; i <= k; i += j-k) factors.pb(s.substr(i,j-k)); 21 | } 22 | return factors; 23 | } 24 | int minRotation(str s) { 25 | int N = sz(s); s += s; 26 | vs d = duval(s); int ind = 0, ans = 0; 27 | while (ans+sz(d[ind]) < N) ans += sz(d[ind++]); 28 | while (ind && d[ind] == d[ind-1]) ans -= sz(d[ind--]); 29 | return ans; 30 | } 31 | -------------------------------------------------------------------------------- /Implementations/content/strings (14)/Light/Manacher.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Source: http://codeforces.com/blog/entry/12143 3 | * Time: O(N) 4 | * Description: length of largest palindrome centered at each character of string 5 | * and between every consecutive pair 6 | * Verification: http://www.spoj.com/problems/MSUBSTR/ 7 | */ 8 | 9 | vi manacher(str _S) { 10 | str S = "@"; each(c,_S) S += c, S += "#"; 11 | S.bk = '&'; 12 | vi ans(sz(S)-1); int lo = 0, hi = 0; 13 | FOR(i,1,sz(S)-1) { 14 | if (i != 1) ans[i] = min(hi-i,ans[hi-i+lo]); 15 | while (S[i-ans[i]-1] == S[i+ans[i]+1]) ++ans[i]; 16 | if (i+ans[i] > hi) lo = i-ans[i], hi = i+ans[i]; 17 | } 18 | ans.erase(begin(ans)); 19 | F0R(i,sz(ans)) if (i%2 == ans[i]%2) ++ans[i]; 20 | return ans; 21 | } 22 | /// Usage: ps(manacher("abacaba")) 23 | -------------------------------------------------------------------------------- /Implementations/content/strings (14)/Light/MinRotation.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: minimum cyclic shift 3 | * Time: O(N) 4 | * Source: KACTL 5 | * Verification: https://cses.fi/problemset/task/1110/ 6 | */ 7 | 8 | int minRotation(str s) { 9 | int a = 0, N = sz(s); s += s; 10 | F0R(b,N) F0R(i,N) { 11 | // a is current best rotation found up to b-1 12 | if (a+i==b || s[a+i] s[b+i]) { a = b; break; } // new best found 15 | } 16 | return a; 17 | } 18 | -------------------------------------------------------------------------------- /Implementations/content/strings (14)/Light/ReverseBW (14.4).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Used only once. Burrows-Wheeler Transform appends 3 | * \# to a string, sorts the rotations of the string in increasing order, 4 | * and constructs a new string that contains the last character 5 | * of each rotation. This function reverses the transform. 6 | * Time: O(N\log N) 7 | * Source: GeeksForGeeks 8 | * Verification: https://cses.fi/problemset/task/1113/ 9 | */ 10 | 11 | str reverseBW(str t) { 12 | vi nex(sz(t)); iota(all(nex),0); 13 | stable_sort(all(nex),[&t](int a,int b){return t[a]> solve(str s) { 15 | int N = sz(s); SuffixArray A,B; 16 | A.init(s); reverse(all(s)); B.init(s); 17 | V> runs; 18 | for (int p = 1; 2*p <= N; ++p) { // do in O(N/p) for period p 19 | for (int i = 0, lst = -1; i+p <= N; i += p) { 20 | int l = i-B.getLCP(N-i-p,N-i), r = i-p+A.getLCP(i,i+p); 21 | if (l > r || l == lst) continue; 22 | runs.pb({lst = l,r,p}); // for each i in [l,r], 23 | } // s.substr(i,p) == s.substr(i+p,p) 24 | } 25 | return runs; 26 | } -------------------------------------------------------------------------------- /Implementations/content/strings (14)/Light/Trie (14.1).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: insert int, query max xor with some int in the trie 3 | * Time: O(MXBIT) 4 | * Source: CF Algorithms Gym 5 | * Verification: January Easy 2018 - Shubham and Subarray Xor 6 | */ 7 | 8 | template struct Trie { 9 | int nex[SZ][2], sz[SZ], num = 0; // num is last node in trie 10 | // change 2 to 26 for lowercase letters 11 | Trie() { memset(nex,0,sizeof nex); memset(sz,0,sizeof sz); } 12 | void ins(ll x, int a = 1) { // insert or delete 13 | int cur = 0; sz[cur] += a; 14 | R0F(i,MXBIT) { 15 | int t = (x>>i)&1; 16 | if (!nex[cur][t]) nex[cur][t] = ++num; 17 | sz[cur = nex[cur][t]] += a; 18 | } 19 | } 20 | ll test(ll x) { // compute max xor 21 | if (!sz[0]) return -INF; // no elements in trie 22 | int cur = 0; 23 | R0F(i,MXBIT) { 24 | int t = ((x>>i)&1)^1; 25 | if (!nex[cur][t] || !sz[nex[cur][t]]) t ^= 1; 26 | cur = nex[cur][t]; if (t) x ^= 1LL< struct TrieAlpha { 6 | int nex[SZ][26], sz[SZ], num = 0; // num is last node in trie 7 | // change 2 to 26 for lowercase letters 8 | TrieAlpha() { memset(nex,0,sizeof nex); memset(sz,0,sizeof sz); } 9 | void ins(str x, int a) { // insert or delete 10 | int cur = 0; sz[cur] += a; 11 | F0R(i,sz(x)) { 12 | int t = x[i]-'a'; 13 | if (!nex[cur][t]) nex[cur][t] = ++num; 14 | sz[cur = nex[cur][t]] += a; 15 | } 16 | } 17 | }; -------------------------------------------------------------------------------- /Implementations/content/strings (14)/Light/Z (14.3).h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: \texttt{f[i]} is the max \texttt{len} such that 3 | * \texttt{s.substr(0,len) == s.substr(i,len)} 4 | * Time: O(N) 5 | * Source: http://codeforces.com/blog/entry/3107 6 | * Verification: POI 12 Template, https://codeforces.com/contest/1137/problem/B 7 | */ 8 | 9 | vi z(str s) { 10 | int N = sz(s), L = 1, R = 0; s += '#'; 11 | vi ans(N); ans[0] = N; 12 | FOR(i,1,N) { 13 | if (i <= R) ans[i] = min(R-i+1,ans[i-L]); 14 | while (s[i+ans[i]] == s[ans[i]]) ++ans[i]; 15 | if (i+ans[i]-1 > R) L = i, R = i+ans[i]-1; 16 | } 17 | return ans; 18 | } 19 | vi getPrefix(str a, str b) { // find prefixes of a in b 20 | vi t = z(a+b); t = vi(sz(a)+all(t)); 21 | each(u,t) ckmin(u,sz(a)); 22 | return t; 23 | } 24 | /// Usage: pr(z("abcababcabcaba"),getPrefix("abcab","uwetrabcerabcab")); 25 | -------------------------------------------------------------------------------- /Implementations/content/strings (14)/chapter.tex: -------------------------------------------------------------------------------- 1 | \chapter{Strings} 2 | 3 | \section{Light} 4 | \kactlimport{Light/KMP.h} 5 | \kactlimport{Light/Z (14.3).h} 6 | \kactlimport{Light/Manacher.h} 7 | % \kactlimport{Light/MinRotation.h} 8 | \kactlimport{Light/LyndonFactor.h} 9 | \kactlimport{Light/HashRange (14.2).h} 10 | \kactlimport{Light/ReverseBW (14.4).h} 11 | \kactlimport{Light/AhoCorasickFixed.h} 12 | \kactlimport{Light/SuffixArray (14.4).h} 13 | \kactlimport{Light/SuffixArrayLinear.h} 14 | \kactlimport{Light/TandemRepeats.h} 15 | 16 | \section{Heavy} 17 | \kactlimport{Heavy/PalTree.h} 18 | \kactlimport{Heavy/SuffixAutomaton.h} 19 | \kactlimport{Heavy/SuffixTree.h} -------------------------------------------------------------------------------- /Implementations/content/test-session/test-session.tex: -------------------------------------------------------------------------------- 1 | \documentclass[10pt, a4paper, notitlepage]{report} 2 | \usepackage{kactlpkg} 3 | \kactlcontentdir{content} 4 | 5 | \university{MIT}{}{} 6 | 7 | \begin{document} 8 | \begin{multicols*}{3} 9 | \kactlchapter{test-session} 10 | \end{multicols*} 11 | \end{document} 12 | -------------------------------------------------------------------------------- /Implementations/content/tex/mit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bqi343/cp-notebook/292c614b7b83c355b188234966b3b336bc009f16/Implementations/content/tex/mit.png -------------------------------------------------------------------------------- /Implementations/content/various/BIT.kt: -------------------------------------------------------------------------------- 1 | class BIT() { 2 | val v = LongArray(SZ) 3 | fun upd(_a: Int, b: Long) { 4 | var a = _a 5 | while (a < SZ) { 6 | v[a] += b 7 | a += (a and -a) 8 | } 9 | } 10 | fun query(_a: Int): Long { 11 | var a = _a 12 | var ans: Long = 0 13 | while (a > 0) { 14 | ans += v[a] 15 | a -= (a and -a) 16 | } 17 | return ans 18 | } 19 | } -------------------------------------------------------------------------------- /Implementations/content/various/BumpAllocator.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: When you need to dynamically allocate many objects and don't care about freeing them. 3 | * "new X" otherwise has an overhead of something like 0.05us + 16 bytes per allocation. 4 | * Source: Simon Lindholm 5 | * Status: tested 6 | */ 7 | 8 | // Either globally or in a single class: 9 | static char buf[450 << 20]; 10 | void* operator new(size_t s) { 11 | static size_t i = sizeof buf; assert(s < i); 12 | return (void*)&buf[i -= s]; 13 | } 14 | void operator delete(void*) {} 15 | -------------------------------------------------------------------------------- /Implementations/content/various/BumpAllocatorSTL.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Unused. BumpAllocator for STL containers. 3 | * Source: Simon Lindholm 4 | * Usage: vector>> ed(N); 5 | * Status: tested 6 | */ 7 | 8 | char buf[450 << 20] alignas(16); 9 | size_t buf_ind = sizeof buf; 10 | template struct small { 11 | typedef T value_type; 12 | small() {} 13 | template small(const U&) {} 14 | T* allocate(size_t n) { 15 | buf_ind -= n * sizeof(T); 16 | buf_ind &= 0 - alignof(T); 17 | return (T*)(buf + buf_ind); 18 | } 19 | void deallocate(T*, size_t) {} 20 | }; 21 | -------------------------------------------------------------------------------- /Implementations/content/various/CircularLCS.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Used only twice. For strs $A,B$ calculates 3 | * longest common subsequence of $A$ with all rotations of $B$ 4 | * Time: O(|A|\cdot |B|) 5 | * Source: gs14004, oj.uz 6 | * Verification: https://oj.uz/problem/view/IZhO13_rowords 7 | * also see B from https://codeforces.com/gym/101657/standings 8 | */ 9 | 10 | int circular_lcs(str A, str B) { 11 | B += B; 12 | int max_lcs = 0; 13 | V dif_left(sz(A)+1,vb(sz(B)+1)), dif_up(sz(A)+1,vb(sz(B)+1)); 14 | auto recalc = [&](int x, int y) { assert(x && y); 15 | int res = (A.at(x-1) == B.at(y-1)) | 16 | dif_up[x][y-1] | dif_left[x-1][y]; 17 | dif_left[x][y] = res-dif_up[x][y-1]; 18 | dif_up[x][y] = res-dif_left[x-1][y]; 19 | }; 20 | FOR(i,1,sz(A)+1) FOR(j,1,sz(B)+1) recalc(i,j); 21 | F0R(j,sz(B)/2) { 22 | // 1. zero out dp[.][j], update dif_left and dif_right 23 | if (j) for (int x = 1, y = j; x <= sz(A) && y <= sz(B); ) { 24 | int pre_up = dif_up[x][y]; 25 | if (y == j) dif_up[x][y] = 0; 26 | else recalc(x,y); 27 | (pre_up == dif_up[x][y]) ? ++x : ++y; 28 | } 29 | // 2. calculate LCS(A[0:sz(A)),B[j:j+sz(B)/2)) 30 | int cur_lcs = 0; 31 | FOR(x,1,sz(A)+1) cur_lcs += dif_up[x][j+sz(B)/2]; 32 | ckmax(max_lcs,cur_lcs); 33 | } 34 | return max_lcs; 35 | } -------------------------------------------------------------------------------- /Implementations/content/various/Decimal.py: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Arbitrary-precision decimals 3 | * Source: https://docs.python.org/3/library/decimal.html 4 | */ 5 | 6 | from decimal import * 7 | 8 | getcontext().prec = 100 # how many digits of precision 9 | print(Decimal(1) / Decimal(7)) # 0.142857142857... 10 | print(Decimal(10) ** -100) # 1E-100 -------------------------------------------------------------------------------- /Implementations/content/various/Knapsack.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Linear Time Knapsack w/ Bounded Weights 3 | * Time: O(N\cdot (\text{max weight})) 4 | * Source: 5 | * https://chaoxuprime.com/posts/2018-12-18-subset-sum-through-balancing.html 6 | * https://stackoverflow.com/questions/18821453/bounded-knapsack-special-case-small-individual-item-weight-is-small-compared-t 7 | * Verification: GP of Bytedance 2020 F 8 | */ 9 | 10 | const int BIG = 20000; 11 | array dp, tmp; 12 | 13 | int solve(vi a) { 14 | int n = sz(a), ind = 0, sum = 0; 15 | while (ind < n && sum+a[ind] <= c) sum += a[ind++]; 16 | if (ind == n) return sum; 17 | F0R(i,2*BIG+1) dp[i] = ind+1, tmp[i] = ind; 18 | dp[BIG+sum-c] = 0; 19 | FOR(i,ind,n) { 20 | R0F(j,BIG+1) ckmin(dp[j+a[i]],dp[j]); 21 | ROF(j,BIG,2*BIG+1) while (tmp[j] > dp[j]) 22 | tmp[j] --, ckmin(dp[j-a[tmp[j]]],tmp[j]+1); 23 | } 24 | R0F(i,BIG+1) if (dp[i] != ind+1) return c+i-BIG; // must return 25 | } -------------------------------------------------------------------------------- /Implementations/content/various/Main.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Author: Andrew He 3 | * Description: Basic template/info for Java 4 | */ 5 | 6 | import java.util.*; 7 | import java.math.*; 8 | import java.io.*; 9 | public class Main { 10 | public static void main(String[] args) throws Exception { 11 | BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 12 | PrintStream out = System.out; 13 | StringTokenizer st = new StringTokenizer(br.readLine()); 14 | assert st.hasMoreTokens(); // enable with java -ea main 15 | out.println("v=" + Integer.parseInt(st.nextToken())); 16 | ArrayList a = new ArrayList<>(); 17 | a.add(1234); a.get(0); a.remove(a.size()-1); a.clear(); 18 | } 19 | } -------------------------------------------------------------------------------- /Implementations/content/various/Python3.py: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Python review. 3 | * Source: own 4 | * Verification: 5 | * https://codeforces.com/contest/1091/problem/G 6 | * https://open.kattis.com/problems/catalansquare 7 | */ 8 | 9 | from math import * 10 | import sys, random 11 | def nextInt(): 12 | return int(input()) 13 | def nextStrs(): 14 | return input().split() 15 | def nextInts(): 16 | return list(map(int,nextStrs())) 17 | 18 | n = nextInt() 19 | v = [n] 20 | def process(x): 21 | global v 22 | x = abs(x) 23 | V = [] 24 | for t in v: 25 | g = gcd(t,x) 26 | if g != 1: 27 | V.append(g) 28 | if g != t: 29 | V.append(t//g) 30 | v = V 31 | for i in range(50): 32 | x = random.randint(0,n-1) 33 | if gcd(x,n) != 1: 34 | process(x) 35 | else: 36 | sx = x*x%n # assert(gcd(sx,n) == 1) 37 | print(f"sqrt {sx}") 38 | sys.stdout.flush() 39 | X = nextInt() 40 | process(x+X) 41 | process(x-X) 42 | print(f'! {len(v)}',end='') 43 | for i in v: 44 | print(f' {i}',end='') 45 | print() 46 | sys.stdout.flush() # sys.exit(0) -> exit 47 | # sys.setrecursionlimit(int(1e9)) -> stack size 48 | # print(f'{ans:=.6f}') -> print ans to 6 decimal places -------------------------------------------------------------------------------- /Implementations/content/various/SmallPtr.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Unused. A 32-bit pointer that points into BumpAllocator memory. 3 | * Source: Simon Lindholm 4 | * Status: tested 5 | */ 6 | 7 | #include "BumpAllocator.h" 8 | 9 | template struct ptr { 10 | unsigned ind; 11 | ptr(T* p = 0) : ind(p ? unsigned((char*)p - buf) : 0) { 12 | assert(ind < sizeof buf); } 13 | T& operator*() const { return *(T*)(buf + ind); } 14 | T* operator->() const { return &**this; } 15 | T& operator[](int a) const { return (&**this)[a]; } 16 | explicit operator bool() const { return ind; } 17 | }; 18 | -------------------------------------------------------------------------------- /Implementations/content/various/Ycombinator.h: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: wraps a lambda so it can call itself 3 | * Source: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2016/p0200r0.html 4 | */ 5 | 6 | namespace std { 7 | 8 | template 9 | class y_combinator_result { 10 | Fun fun_; 11 | public: 12 | template 13 | explicit y_combinator_result(T &&fun): fun_(std::forward(fun)) {} 14 | 15 | template 16 | decltype(auto) operator()(Args &&...args) { 17 | return fun_(std::ref(*this), std::forward(args)...); 18 | } 19 | }; 20 | 21 | template 22 | decltype(auto) y_combinator(Fun &&fun) { 23 | return y_combinator_result>(std::forward(fun)); 24 | } 25 | 26 | } // namespace std 27 | 28 | void y_comb_demo() { 29 | cout << y_combinator([](auto gcd, int a, int b) -> int { 30 | return b == 0 ? a : gcd(b, a % b); 31 | })(20,30) << "\n"; // outputs 10 32 | } -------------------------------------------------------------------------------- /Implementations/content/various/ktLinks.txt: -------------------------------------------------------------------------------- 1 | 2 | /** useful links 3 | * https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-array/index.html 4 | * https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/-array-list/index.html 5 | * https://kotlinlang.org/docs/reference/ranges.html 6 | * https://alvinalexander.com/source-code-kotlin-sortedWith-syntax-lambda-examples 7 | * https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/also.html 8 | * https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/binary-search.html 9 | * https://kotlinlang.org/docs/reference/control-flow.html 10 | */ 11 | -------------------------------------------------------------------------------- /Implementations/kactl.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bqi343/cp-notebook/292c614b7b83c355b188234966b3b336bc009f16/Implementations/kactl.pdf -------------------------------------------------------------------------------- /Implementations/kactl_color.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bqi343/cp-notebook/292c614b7b83c355b188234966b3b336bc009f16/Implementations/kactl_color.pdf -------------------------------------------------------------------------------- /Implementations/test-compiles.sh: -------------------------------------------------------------------------------- 1 | FILE="$1" 2 | echo "TEST COMPILE "$FILE 3 | echo " 4 | #include \"../content/contest/Template.cpp\" 5 | #include \"../content/contest/CppIO.h\" 6 | #include \"../content/$FILE\" 7 | " >build/temp.cpp 8 | # g++ -Wall -Wextra -Wfatal-errors -Wconversion -std=c++11 build/temp.cpp && rm a.out build/temp.cpp 9 | g++ -Wall -Wextra -Wfatal-errors -std=c++11 build/temp.cpp && rm a.out build/temp.cpp 10 | # g++ -std=c++14 build/temp.cpp && rm a.out build/temp.cpp -------------------------------------------------------------------------------- /Implementations/test-session.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bqi343/cp-notebook/292c614b7b83c355b188234966b3b336bc009f16/Implementations/test-session.pdf -------------------------------------------------------------------------------- /Implementations/testAll.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | 4 | for root, dirs, files in os.walk("/Users/benq/Documents/USACO/Implementations",topdown=False): 5 | # print("?",root,dirs,files) 6 | for name in files: 7 | if name.endswith(".h") and name[0].isupper(): 8 | path = root+"/"+name 9 | path = path[path.find("content/")+len("content/"):] 10 | if "CppIO" in path or "BigInt" in path: 11 | continue 12 | p = subprocess.Popen(['sh', 'test-compiles.sh',path], stdin=subprocess.PIPE, stdout=subprocess.PIPE) 13 | res, _ = p.communicate() 14 | print(res.decode("utf-8").rstrip()) -------------------------------------------------------------------------------- /Other Implementations/04 - Sorting and Searching/Binary Search (4.3).cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: Basic example of binary search 3 | * Guess the Number 4 | * https://open.kattis.com/problems/guess 5 | */ 6 | 7 | void binarySearch() { 8 | int lo = 1, hi = 1000; 9 | while (1) { 10 | int mid = (lo+hi)/2; 11 | cout << mid << endl; 12 | string res; cin >> res; 13 | if (res == "correct") return 0; 14 | else if (res == "lower") hi = mid-1; 15 | else lo = mid+1; 16 | } 17 | } -------------------------------------------------------------------------------- /Other Implementations/04 - Sorting and Searching/Coordinate Compression.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: demonstrates use of map 3 | * Source: Own 4 | * Verification: POI 12 - The Bus 5 | */ 6 | 7 | void compress(vector& x, int ind) { 8 | map m; 9 | trav(a,x) m[a[ind]] = 0; 10 | int co = 0; trav(a,m) a.s = co++; 11 | trav(a,x) a[ind] = m[a[ind]]; 12 | } -------------------------------------------------------------------------------- /Other Implementations/04 - Sorting and Searching/Interval Cover (4.1).cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: example of greedy algorithm 3 | * Source: Own 4 | * Verification: https://open.kattis.com/problems/intervalcover 5 | * actually, you need to account for A=B and add epsilons but w/e 6 | */ 7 | 8 | vi solve(double A, double B, vector> in) { // cover [A,B] with intervals from in 9 | pair mx = {A,-1}; 10 | vi ans; 11 | int nex = 0; 12 | 13 | sort(all(in)); 14 | while (mx.f < B) { 15 | double cur = mx.f; 16 | while (nex < sz(in) && in[nex].f.f <= cur) 17 | mx = max(mx,{in[nex].f.s,in[nex].s}), nex++; 18 | if (mx.f == cur) return {}; 19 | ans.pb(mx.s); 20 | } 21 | 22 | return ans; 23 | } 24 | -------------------------------------------------------------------------------- /Other Implementations/04 - Sorting and Searching/README.md: -------------------------------------------------------------------------------- 1 | # 4 - Sorting & Searching 2 | 3 | [CPC.4](https://github.com/SuprDewd/T-414-AFLV/tree/master/04_problem_solving_paradigms) 4 | 5 | ## 2 6 | 7 | * Complete Search 8 | * Tutorial 9 | * CPH (5, Complete Search) 10 | * Problems 11 | * [Maximum Clique Problem](https://en.wikipedia.org/wiki/Clique_problem) 12 | * [Cracker Barrel Game](https://open.kattis.com/problems/crackerbarrel) 13 | * [Coloring Graphs](https://open.kattis.com/problems/coloring) 14 | 15 | ## 6 16 | * Parallel Binary Search 17 | * Tutorial 18 | * CP Guide 15.5.3 19 | * Problem 20 | * [Meteors](https://szkopul.edu.pl/problemset/problem/7JrCYZ7LhEK4nBR5zbAXpcmM/site/?key=statement) 21 | -------------------------------------------------------------------------------- /Other Implementations/04 - Sorting and Searching/Ternary Search (8.3).cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: solve for min on functions which are strictly decreasing then strictly increasing 3 | * Source: own 4 | */ 5 | 6 | double eval(double x) { 7 | return (x-5)*(x-5); 8 | } 9 | 10 | double ternary(double l, double r) { 11 | if (abs(r-l) <= 1e-9) return (l+r)/2; 12 | double l1 = (2*l+r)/3, r1 = (l+2*r)/3; 13 | return eval(l1) < eval(r1) ? ternary(l,r1) : ternary(l1,r); 14 | } // ternary(-100,100) = 5 -------------------------------------------------------------------------------- /Other Implementations/06 - DP/Distinct Subsequences (6).cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: DP eliminates overcounting 3 | * Source: Own 4 | * Verification: CSES String Removals 5 | * https://cses.fi/problemset/task/1149/ 6 | */ 7 | 8 | mi distinct(const string& S) { 9 | vmi tot(26); mi ans = 1; // tot[i] stands for number of distinct strings ending with character 'a'+i 10 | trav(c,S) tie(ans,tot[c-'a']) = mp(2*ans-tot[c-'a'],ans); 11 | return ans; 12 | } 13 | -------------------------------------------------------------------------------- /Other Implementations/06 - DP/Divide And Conquer (15.4).cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: ? 3 | * Source: Own 4 | * Verification: CEOI 2004 Two Sawmills 5 | */ 6 | 7 | void divide(int lo, int hi, int L, int R) { 8 | if (lo > hi) return; 9 | int mid = (lo+hi)/2; 10 | pair tmp = {1e18,-1}; 11 | FOR(i,max(mid+1,L),R+1) 12 | tmp = min(tmp,{calc(0,mid)+calc(mid+1,i) 13 | +calc(i+1,n),i}); // find lowest optimal index 14 | ans = min(ans,tmp.f); 15 | divide(lo,mid-1,L,tmp.s); // assume optimal index is non-decreasing 16 | divide(mid+1,hi,tmp.s,R); 17 | } -------------------------------------------------------------------------------- /Other Implementations/06 - DP/HamilPath (12.2).cpp: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: computes number of paths from N-2 to N-1 which 3 | * pass through each of the cities 0 to N-1 exactly once, mod 10^9+7 4 | * Time: O(N^22^N) 5 | * Source: own 6 | * Verification: CSES Hamiltonian Flights 7 | * https://cses.fi/problemset/task/1690/ 8 | */ 9 | 10 | int N; 11 | bool adj[20][20]; 12 | mi dp[18][1<<18]; 13 | 14 | mi solve() { 15 | F0R(i,N-2) if (adj[N-2][i]) dp[i][1< "Questions.md" first. 14 | --------------------------------------------------------------------------------