├── Easy ├── 1--ngr---basic-radar.cpp ├── 10-pin-bowling-scores.cs ├── 1000000000d-world.cpp ├── 111-rubiks-cube-movements.js ├── 1d-bush-fire.c ├── 1d-spreadsheet.cpp ├── 2nd-degree-polynomial---simple-analysis.cpp ├── 7-segment-scanner.cpp ├── a-bunny-and-carrots.cpp ├── a-childs-play.c ├── a-mountain-of-a-mole-hill.py ├── abcdefghijklmnopqrstuvwxyz.cpp ├── addem-up.py ├── agent-x-mission-1-the-caesar-cipher.cpp ├── an-adventure-in-the-fantasy-world.rs ├── annihilation.cpp ├── are-the-clumps-normal.cpp ├── artificial-emotional-intelligence.cs ├── ascii-art-the-drunken-bishop-algorithm.rs ├── ascii-art.cpp ├── ascii-worms.rs ├── asteroids.cpp ├── auto-pickup.cpp ├── azimut.rs ├── balanced-ternary-computer-encode.c ├── bank-robbers.js ├── battle-of-heroes.cpp ├── benfords-law.cpp ├── bijective-numeration.rs ├── binary-image.py ├── blackjack-solver.py ├── blowing-fuse.c ├── body-weight-is-a-girls-secret.rs ├── brackets-extreme-edition.c ├── brick-in-the-wall.c ├── builk-email-generator.py ├── buzzle.cpp ├── caesar-is-the-chief.cpp ├── calculator.cpp ├── card-counting-when-easily-distracted.cpp ├── catching-up.cpp ├── character-replacement-problem.cpp ├── cheap-choices.rs ├── chuck-norris.cpp ├── code-breaker-puzzle.py ├── container-terminal.cpp ├── cosmic-love.cpp ├── count-as-i-count.cpp ├── count-your-coins.cpp ├── crack-the-trio-code.rs ├── crazy-list.cpp ├── create-the-longest-sequence-of-1s.c ├── create-turn-here-signs.rs ├── credit-card-verifier-luhns-algorithm.cpp ├── crop-circles.cs ├── custom-game-of-life.cpp ├── darts-checkout-routes.rs ├── darts.cpp ├── dead-mens-shot.c ├── decode-the-message.cpp ├── defibrillators.cpp ├── detective-geek.rs ├── detective-pikaptcha-ep1.c ├── detective-pikaptcha-ep2.c ├── deus-hex-machina.py ├── dice-handedness.py ├── digital-scoreboard.cpp ├── disordered-first-contact.js ├── distributing-candy.cpp ├── dolbears-law.cpp ├── dungeons-and-maps.cpp ├── duo-combinations.rs ├── egyptian-multiplication.rs ├── embedded-chessboards.cpp ├── encryptiondecryption-of-enigma-machine.c ├── equivalent-resistance-circuit-building.java ├── euclids-algorithm.cpp ├── extended-hamming-codes.py ├── faro-shuffle.cpp ├── fax-machine.cpp ├── feature-extraction.cpp ├── fibonaccis-rabbit.rs ├── firecontrol.cpp ├── fix-the-networks.rs ├── flip-the-sign.cpp ├── frame-the-picture.cpp ├── gdq---binary-coded-decimal-clock.cpp ├── genetics-and-computers---part-1.py ├── ghost-legs.c ├── graffiti-on-the-fence.cpp ├── happy-numbers.cpp ├── hello-world.php ├── hidden-messages-in-images.cpp ├── hooch-clash.sh ├── horse-racing-duals.cpp ├── horse-racing-hyperduals.c ├── how-time-flies.py ├── hunger-games.py ├── in-stereo.py ├── insert-to-string.cpp ├── ipv6-shortener.py ├── is-that-a-possible-word-ep1.cpp ├── isbn-check-digit.c ├── island-escape.cpp ├── jack-silver-the-casino.c ├── kangaroo-words.cpp ├── kiss-the-girls.cpp ├── largest-number.py ├── library-dependencies.rs ├── logic-gates.cpp ├── logically-reasonable-inequalities.cpp ├── longest-coast.cpp ├── low-resolution-whats-the-shape.cpp ├── lumen.c ├── magic-string.rs ├── mandelbrot-set-approximation.rs ├── mars-lander-episode-1.py ├── match-dna-sequence.rs ├── max-area.cpp ├── may-the-triforce-be-with-you.c ├── merlins-magic-square.cpp ├── messed-up-mosaics.cpp ├── metric-units.cs ├── mime-type.py ├── minesweeper-level-generator.cpp ├── minimal-palindrome-distance.cpp ├── mirrors.cpp ├── monday-tuesday-happy-days.py ├── morellets-random-lines.js ├── mountain-map-convergence.py ├── mountain-map.py ├── moves-in-maze.cpp ├── murder-in-the-village.py ├── nato-alphabets-odd-uncles.cpp ├── nature-of-quadrilaterals.c ├── next-growing-number.cpp ├── number-derivation.py ├── number-formatting.rs ├── number-of-digits.rs ├── number-partition.cpp ├── object-insertion.cpp ├── odd-quad-out.cpp ├── offset-arrays.py ├── onboarding.cpp ├── order-of-succession.py ├── organic-compounds.java ├── panel-count.rs ├── periodic-table-spelling.rs ├── pirates-treasure.c ├── playing-card-odds.rs ├── power-of-thor-1.js ├── prefix-code.cpp ├── probability-for-dummies.cpp ├── queen-control.cpp ├── random-walk.cpp ├── rectangle-partition.cpp ├── rectangular-block-spinner.py ├── retro-typewriter-art.cpp ├── reverse-fizzbuzz.rb ├── reverse-minesweeper.cpp ├── robot-reach.cpp ├── robot-show.cpp ├── rock-paper-scissors-lizard-spock.cpp ├── rocks-papers-scissors-es.cpp ├── roocks-movements.c ├── rotating-arrows.cpp ├── rugby-score.c ├── sand-fall.rs ├── saving-snoopy.cpp ├── scrabble-score.rs ├── self-driving-car-testing.c ├── shadow-casting.cpp ├── shoot-enemy-aircraft.cpp ├── should-bakers-be-frugal.cpp ├── simple-auto-scaling.cpp ├── simple-awale.js ├── simple-load-balancing.cpp ├── six-degrees-of-kevin-bacon.cpp ├── smooth.sh ├── snail-run.cpp ├── snake-sort-2d.cpp ├── someones-acting-sus----.py ├── sparse-matmul.rs ├── stall-tilt.py ├── stunning-numbers.rs ├── substitution-encoding.cpp ├── sudoku-validator.py ├── sum-of-spirals-diagonals.cpp ├── survey-prediction.rs ├── sweet-spot.cpp ├── table-of-contents.rs ├── teds-compiler.cpp ├── temperatures.js ├── text-formatting.py ├── the-broken-editor.cpp ├── the-dart-101.c ├── the-descent.js ├── the-electrician-apprentice.cs ├── the-helpdesk.cpp ├── the-leaking-bathtub.rs ├── the-lost-child-episode-1.cpp ├── the-michelangelo-code.py ├── the-mystic-rectangle.cpp ├── the-other-side.rs ├── the-prime-twins---part-one.rs ├── the-river-i.c ├── the-river-ii.c ├── the-travelling-salesman-problem.c ├── the-weight-of-words.cpp ├── tictactoe.py ├── timer-for-clash-of-code.rs ├── treasure-hunt.cpp ├── tree-paths.rb ├── triangle-toggle.rs ├── tricky-number-verifier.py ├── ulam-spiral.py ├── unique-prefixes.cpp ├── unit-fractions.c ├── van-eck.cpp ├── vectors-in-variables-dimensions.py ├── video-comments.py ├── walk-on-a-die.rs ├── what-is-your-garden-worth.rs ├── whats-so-complex-about-mandelbrot.c ├── where-am-i-going.rs ├── wheres-wally.cpp ├── word-search-for-programmers.rs ├── wordle-colorizer.cpp ├── xml-mdf-2016.cpp ├── zeckendorf-representation-part-i.cpp └── zhiwei-sun-squares.cpp ├── Hard ├── blunder-episode-2.cpp ├── cgx-formatter.cpp ├── chess-board-analyzer.cpp ├── death-first-search-episode-2.cpp ├── doubly-solved-rubiks-cube.py ├── hanoi-tower.cpp ├── levenshtein-distance.cpp ├── max-rect.cpp ├── the-labyrinthe.cpp └── vox-codei-episode-1.cpp ├── LICENSE ├── Medium ├── 10101.c ├── 16x16-sudoku.rs ├── a-star-exercise.cpp ├── ancestors-&-descendants.cpp ├── aneo.c ├── ascii-art-glass-stacking.c ├── ascii-graph.c ├── bag-of-balls.cpp ├── barcode-scanner.py ├── bender-episode-1.cpp ├── binary-search-tree-traversal.cpp ├── binary-sequence.py ├── bingo.java ├── bit-count-to-limit.cpp ├── boarding-passes-ready.cpp ├── bouncing-barry.cs ├── box-of-cigars.c ├── brackets-enhanced-edition.js ├── brackets-extended-edition.c ├── brackets-ultimate-edition.js ├── bruce-lee.js ├── bulgarian-solitaire.cpp ├── bulls-and-cows.c ├── bust-speeding-vehicles.c ├── byte-pair-encoding.py ├── cards-castle.c ├── carmichael-numbers.c ├── cgfunge-interpreter.py ├── cgs-minifier.cpp ├── constrained-latin-squares.cpp ├── conway-sequence.cpp ├── count-of-primes-in-a-number-grid.c ├── counting-squares-on-pegs.js ├── criminal.cpp ├── digit-sum-successor.cpp ├── divide-the-factorial.rb ├── dominoes-path.cpp ├── don't-panic-episode-1.cpp ├── drug-interactions.cpp ├── dwarfs-standing-on-the-shoulders-of-giants.cpp ├── dynamic-sorting.cs ├── elementary-cellular-automaton.c ├── entry-code.rs ├── equalizing-arrays.cpp ├── factorial-vs-exponential.c ├── fair-numbering.cpp ├── find-the-replacement.cpp ├── flood-fill-example.cpp ├── folding-a-note.py ├── folding-paper.cpp ├── forest-fire.cpp ├── game-of-life.c ├── go-competition.c ├── goro-want-chocolate.cpp ├── gravity-tumbler.py ├── gravity.c ├── green-valleys.cpp ├── guessing-n-cheating.c ├── hacking-at-robbercity.js ├── halting-sequences.cpp ├── hexagonal-maze.cpp ├── huffman-code.cpp ├── inversion-count.cs ├── ip-mask-calculating.cpp ├── join-the-dots.rs ├── jumping-frogs.cpp ├── kaprekars-routine.js ├── knights-jam.cpp ├── langtons-ant.c ├── length-of-syracuse-conjecture-sequence.cpp ├── locked-in-gear.cpp ├── magic-square.cpp ├── mars-lander-ep2.cpp ├── maximum-sub-sequence.c ├── mayan-calculation.c ├── maze.c ├── mcxxxx-microcontroller-simulation.c ├── micro-assembly.c ├── minesweeper.cpp ├── minimax-exercise.c ├── monthly-system.c ├── mosaic.rs ├── network-cabling.cpp ├── number-of-letters-in-a-number---binary.cpp ├── number-of-paths-between-2-points.c ├── oneway-city.py ├── othello.js ├── photo-booth-transformation.c ├── plague-jr.py ├── playfair-cipher.py ├── porcupine-fever.c ├── propositions-in-freges-ideography.py ├── queneau-numbers.cljs ├── rational-number-tree.cpp ├── rearrange-strings-to-two-numbers.cpp ├── remaining-card.cpp ├── reverse-polish-notation.py ├── reversed-look-and-say.cpp ├── robbery-optimisation.cpp ├── rod-cutting-problem.cpp ├── roman-sorting.rs ├── sandpile-addition.c ├── scrabble.cpp ├── seam-carving.cpp ├── shadows-of-the-knight-episode-1.cpp ├── skynet-revolution-episode-1.cpp ├── snake-encoding.js ├── stock-exchange-losses.cpp ├── sudoku-solver.cpp ├── sum-of-divisors.c ├── telephone-numbers.cpp ├── text-alignment.c ├── the-cash-register.rs ├── the-experience-for-creating-puzzles.c ├── the-fastest.c ├── the-gift.cpp ├── the-grand-festival---i.cpp ├── the-grand-festival---ii.java ├── the-last-crusade-episode-1.cpp ├── the-optimal-urinal-problem.js ├── the-urinal-problem.py ├── there-is-no-spoon-episode-1.cpp ├── these-romans-are-crazy!.cpp ├── tiny-forest.cpp ├── trits-balanced-ternary-computing.c ├── vote-counting.cpp ├── ways-to-make-change.cpp ├── were-going-in-circles.cpp ├── what-the-brainfuck.cpp └── winamax-battle.cpp ├── README.md ├── Very hard └── the-resistance.cpp ├── codingame_banner.png └── link.png /Easy/1--ngr---basic-radar.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Record { 4 | std::string plate, radarName; 5 | long long ts; 6 | 7 | friend std::istream& operator>>(std::istream& is, Record& rec) { 8 | return is >> rec.plate >> rec.radarName >> rec.ts; 9 | } 10 | 11 | friend bool operator<(const Record& lhs, const Record& rhs) { 12 | return lhs.plate < rhs.plate; 13 | } 14 | }; 15 | 16 | int main() 17 | { 18 | std::map records; 19 | Record rec; 20 | int N; 21 | 22 | std::cin >> N; 23 | for (int i = 0; i < N && std::cin >> rec; i++) { 24 | if ( auto it = records.find(rec); it != std::end(records) ) { 25 | records[rec] = ( 3600000 * 13 ) / abs( (int)(rec.ts - it->first.ts) ); 26 | } else { records[rec] = 0; } 27 | } 28 | 29 | for ( auto& [r, v] : records ) 30 | if ( v > 130 ) std::cout << r.plate << " " << v << "\n"; 31 | } -------------------------------------------------------------------------------- /Easy/1000000000d-world.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | std::vector getVec(const std::string& str) { 4 | std::istringstream iss(str); 5 | 6 | return std::vector((std::istream_iterator(iss)), 7 | std::istream_iterator()); 8 | } 9 | 10 | int main() 11 | { 12 | std::string a, b; 13 | getline(std::cin, a); 14 | getline(std::cin, b); 15 | 16 | auto v1{ getVec(a) }, v2{ getVec(b) }; 17 | int64_t ret{0}, n{0}, m{0}, count{0}, times{0}; 18 | 19 | while( n < std::size(v1) ) 20 | { 21 | times = std::min(v1[n], v2[m]); 22 | v1[n] -= times; 23 | v2[m] -= times; 24 | count += times; 25 | ret += times * v1[n+1] * v2[m+1]; 26 | 27 | if ( v1[n] == 0 ) { n += 2; } 28 | if ( v2[m] == 0 ) { m += 2; } 29 | } 30 | std::cout << ret << "\n"; 31 | } 32 | -------------------------------------------------------------------------------- /Easy/111-rubiks-cube-movements.js: -------------------------------------------------------------------------------- 1 | function flatten(a) { return Array.prototype.concat(...a); } 2 | 3 | const dir = "'", rl = 'x', ud = 'y'; 4 | const [r, f1, f2] = [readline().split(' '), readline(), readline()]; 5 | const rubik = [['R', 'L'], ['U', 'D'], ['F', 'B']]; 6 | 7 | const rotate = rot => { 8 | let [[x, y], k] = rot[0] === rl ? [[1, 2], 1] : rot[0] === ud ? [[0, 2], 2] : [[0, 1], 0]; 9 | if (rot[1] === dir) { k = rot[0] === rl ? 2 : rot[0] == ud ? 0 : 1; } 10 | const [X, Y] = rubik[k]; 11 | rubik[k] = [Y, X]; 12 | [rubik[x], rubik[y]] = [rubik[y], rubik[x]]; 13 | }; 14 | 15 | r.forEach(rot => { rotate(rot); }); 16 | 17 | const start = [['R', 'L'], ['U', 'D'], ['F', 'B']]; 18 | const face = (face) => flatten(start)[flatten(rubik).indexOf(face)]; 19 | print(face(f1)); 20 | print(face(f2)); -------------------------------------------------------------------------------- /Easy/1d-bush-fire.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() 7 | { 8 | int tests; 9 | scanf("%d", &tests); fgetc(stdin); 10 | while ( tests-- ) 11 | { 12 | char line[256]; 13 | fgets(line, 256, stdin); 14 | 15 | int l_result = 0; 16 | 17 | for ( int j = 0; j < strlen(line); ++j ) 18 | if ( line[j] == 'f' ) { ++l_result; j+=2; } 19 | 20 | printf("%d\n", l_result); 21 | } 22 | } -------------------------------------------------------------------------------- /Easy/2nd-degree-polynomial---simple-analysis.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Pt { 4 | double x, y; 5 | friend bool operator<(const Pt& lhs, const Pt& rhs) { return lhs.x < rhs.x; } 6 | friend std::ostream& operator<<(std::ostream& o, const Pt& pt) { 7 | return o << std::setprecision(3) << "(" << pt.x << "," << pt.y << ")"; 8 | } 9 | }; 10 | 11 | int main() 12 | { 13 | float a, b, c; 14 | std::set res; 15 | std::cin >> a >> b >> c; std::cin.ignore(); 16 | 17 | res.insert({0, c}); 18 | if ( 0.f == a ) { 19 | if ( 0.f == b ) { res.insert({0 , c}); } 20 | else { res.insert({-c/b, 0}); } 21 | } else { 22 | double delta = b*b - 4*a*c, 23 | x1 = (-b - sqrt(delta)) / (2 * a), 24 | x2 = (-b + sqrt(delta)) / (2 * a); 25 | if ( 0 <= delta ) { 26 | res.insert({ x1, a*x1*x1 + b*x1 + c}); 27 | res.insert({ x2, a*x2*x2 + b*x2 + c}); 28 | } 29 | } 30 | 31 | std::stringstream ss; 32 | std::string out; 33 | for ( const auto& pt : res ) 34 | ss << pt << ","; 35 | out = ss.str(); 36 | out.pop_back(); 37 | std::cout << out << '\n'; 38 | } -------------------------------------------------------------------------------- /Easy/7-segment-scanner.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | static map bin2digit = 10 | { 11 | { 126 , 0 }, // 1111110 12 | { 48 , 1 }, // 0110000 13 | { 109 , 2 }, // 1101101 14 | { 121 , 3 }, // 1111001 15 | { 51 , 4 }, // 0110011 16 | { 91 , 5 }, // 1011011 17 | { 95 , 6 }, // 1011111 18 | { 112 , 7 }, // 1110000 19 | { 127 , 8 }, // 1111111 20 | { 123 , 9 } // 1111011 21 | }; 22 | 23 | int util(char c, int i) { return ( c == ' ' ? 0 : 1 << i ); } 24 | 25 | int main() 26 | { 27 | vector l(3, ""); 28 | for ( int i = 0; i < 3 ; i++ ) { getline(cin, l[i]); } 29 | for ( int i = 0; i < l.at(0).size(); i+=3 ) 30 | { 31 | int bin = util(l[0][i+1], 6 ) + 32 | util(l[1][i+2], 5 ) + util(l[1][i+1], 0 ) + util(l[1][i+0], 1 ) + 33 | util(l[2][i+0], 2 ) + util(l[2][i+1], 3 ) + util(l[2][i+2], 4 ); 34 | assert( bin2digit.find(bin) != bin2digit.end() ); 35 | cout << bin2digit[bin]; 36 | } 37 | cout << endl; 38 | } -------------------------------------------------------------------------------- /Easy/a-bunny-and-carrots.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int m, n, t, col; 6 | std::cin >> m >> n >> t; std::cin.ignore(); 7 | 8 | int ret = 2 * (m+n) ; 9 | std::vector d(n + 2, 0); 10 | d[0] = d[n + 1] = m; 11 | 12 | int i = 0; 13 | while( std::cin >> col ) { 14 | ++d[col]; 15 | 16 | ret += 2; 17 | if ( d[col - 1] >= d[col] ) ret -= 2; 18 | if ( d[col + 1] >= d[col] ) ret -= 2; 19 | if ( d[col] == m ) ret -= 2; 20 | 21 | std::cout << ret << "\n"; 22 | } 23 | } -------------------------------------------------------------------------------- /Easy/a-childs-play.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | char lab[10][521]; 6 | int w, h; 7 | long long op, tmp = 0; 8 | 9 | typedef enum _Direction { 10 | TOP = 1, 11 | BOT = 2, 12 | RIGHT = 3, 13 | LEFT = 4 14 | } Dir; 15 | 16 | typedef struct _Robot { 17 | int x_init, y_init; 18 | int x, y; 19 | Dir d; 20 | } Rob; 21 | 22 | main() 23 | { 24 | Rob rb = { .x_init = 0, .y_init = 0, .x = 0, .y = 0, .d = TOP }; 25 | scanf("%d%d%lld", &w, &h, &op); fgetc(stdin); 26 | 27 | for (int i = 0; i < h; i++) { fgets(lab[i], 521, stdin); 28 | for (int j = 0; j < w; j++) 29 | if (lab[i][j] == 'O' ) { rb.x = i; rb.y = j; rb.x_init = i, rb.y_init = j; break; } } 30 | 31 | while(tmp++ < op) { 32 | switch(rb.d) 33 | { 34 | case TOP: if (lab[--rb.x -1][rb.y ] == '#') { rb.d = RIGHT; } break; 35 | case BOT: if (lab[++rb.x +1][rb.y ] == '#') { rb.d = LEFT; } break; 36 | case RIGHT: if (lab[rb.x ][++rb.y + 1] == '#') { rb.d = BOT; } break; 37 | case LEFT: if (lab[rb.x ][--rb.y - 1] == '#') { rb.d = TOP; } break; 38 | } 39 | if (rb.d == TOP && rb.x == rb.x_init && rb.y == rb.y_init) { tmp = op - (op % tmp); } 40 | } 41 | prin -------------------------------------------------------------------------------- /Easy/a-mountain-of-a-mole-hill.py: -------------------------------------------------------------------------------- 1 | S = 16 2 | res = 0 3 | L = ' '*S 4 | 5 | for _ in range(S): 6 | L, L0 = input(), L 7 | inside = False 8 | for j,c in enumerate(L): 9 | if c=='|' or (c=='+' and L0[j] in '|+'): inside = not inside 10 | elif c=='o' and inside: res += 1 11 | print(res) -------------------------------------------------------------------------------- /Easy/addem-up.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | x = sorted(map(int, input().split())) 3 | 4 | cost = 0 5 | while len(x) > 1: 6 | minSum = x[0] + x[1] 7 | cost += minSum 8 | x = sorted([minSum] + x[2:]) 9 | print(cost) 10 | -------------------------------------------------------------------------------- /Easy/agent-x-mission-1-the-caesar-cipher.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | std::string ciphertext, word, decoded, tmp; 5 | std::set delimiters{ ' ', ',', '.', '?', ';', ':', '!' }; 6 | int key{ 0 }, cmpt; 7 | 8 | getline(std::cin, ciphertext); 9 | std::cin >> word; std::cin.ignore(); 10 | 11 | for ( key = 0; key < 96; ++key ) { 12 | decoded = tmp = ciphertext; 13 | cmpt = 0; 14 | std::for_each(std::begin(decoded), std::end(decoded), [&](char& c) { 15 | c = (( c - key - 32 + 95 ) % 95) + 32; 16 | tmp[cmpt++] = ( delimiters.count(c) ) ? ' ' : c; 17 | }); 18 | 19 | std::istringstream iss(tmp); 20 | for ( const auto& w : std::vector((std::istream_iterator(iss)), 21 | std::istream_iterator()) ) 22 | if ( word == w ) goto end; 23 | } 24 | 25 | end: 26 | std::cout << key << '\n' << decoded << std::endl; 27 | } -------------------------------------------------------------------------------- /Easy/annihilation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef std::string ARROW; 4 | typedef std::pair POS; 5 | 6 | int main() 7 | { 8 | int h, w, turns{0}; 9 | std::map state{}; 10 | 11 | std::cin >> h >> w; std::cin.ignore(); 12 | 13 | for ( auto i = 0; i < h; ++i ) { 14 | std::string line; 15 | getline(std::cin, line); 16 | for ( auto j = 0; j < std::size(line); ++j ) 17 | if( line[j] != '.' ) state[std::pair{i, j}] = line[j]; 18 | } 19 | 20 | while ( !std::empty(state) ) { 21 | std::map< POS, ARROW > next; 22 | for ( auto [pos, arrow] : state ) { 23 | auto x{ pos.first }, y{ pos.second }; 24 | switch(arrow[0]) { 25 | case '^': x = (x - 1 + h) % h; break; 26 | case 'v': x = (x + 1 ) % h; break; 27 | case '<': y = (y - 1 + w) % w; break; 28 | case '>': y = (y + 1 ) % w; break; 29 | } 30 | next[{x, y}] += arrow; 31 | } 32 | 33 | for ( auto it = std::begin(next); std::end(next) != it; ) 34 | if ( std::size(it->second) > 1 ) it = next.erase(it); 35 | else ++it; 36 | 37 | state = next; 38 | ++turns; 39 | } 40 | 41 | std::cout << turns << '\n'; 42 | } -------------------------------------------------------------------------------- /Easy/are-the-clumps-normal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | string N, s_res("Normal"); 9 | int s_prev(0), s_cur(0); 10 | int s_rest (-1); 11 | cin >> N; cin.ignore(); 12 | 13 | for ( int i = 2; i < 10; i++ ) 14 | { 15 | int l_rest = 0; 16 | s_cur = 0; 17 | s_rest = (N[0] - '0') % i; 18 | 19 | for ( auto& c : N ) 20 | { 21 | l_rest = (c - '0') % i; 22 | if ( s_rest != l_rest ) { s_cur++; } 23 | s_rest = l_rest; 24 | } 25 | 26 | if ( s_cur < s_prev ) 27 | { 28 | s_res = to_string(i); 29 | break; 30 | } 31 | s_prev = s_cur; 32 | } 33 | 34 | cout << s_res << endl; 35 | } -------------------------------------------------------------------------------- /Easy/ascii-art.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main() 10 | { 11 | int L, H; 12 | string T, ROW; 13 | vector ascii_input, ascii_output; 14 | string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ?"; // input alphabet 15 | 16 | cin >> L >> H; cin.ignore(); 17 | 18 | getline(cin, T); 19 | 20 | ascii_input = vector(H, ""); 21 | ascii_output = vector(H, ""); 22 | 23 | for (int i = 0; i < H; i++) { getline(cin, ascii_input[i]); } 24 | 25 | for( auto i = 0; i < T.length(); ++i) 26 | { 27 | char s = toupper(T[i]); 28 | if((s < 'A') || (s > 'Z')) { s = '?'; } 29 | int index = alphabet.find(s); 30 | if (index == string::npos) { break; } 31 | 32 | for(auto i=0; i {{ 5 | let mut input_line = String::new(); 6 | io::stdin().read_line(&mut input_line).unwrap(); 7 | input_line.trim_matches('\n').parse::<$t>().unwrap() 8 | }} 9 | } 10 | 11 | fn main() { 12 | let thickness = parse_input!(usize); 13 | let length = parse_input!(usize); 14 | let turns = parse_input!(usize); 15 | 16 | println!(" {}{}{}", "_".repeat(thickness), (" ".to_owned() + "_".repeat(thickness*2+1).as_str()).repeat(turns / 2), (if turns % 2 == 1{" ".to_owned() + "_".repeat(thickness).as_str()} else {"".to_string()})); 17 | println!("|{}{}{}|", " ".repeat(thickness), ("|".to_owned() + " ".repeat(thickness*2+1).as_str()).repeat(turns / 2), (if turns % 2 == 1{"|".to_owned() + " ".repeat(thickness).as_str()} else {"".to_string()})); 18 | for _ in 2..length { 19 | println!("{}|", ("|".to_owned() + " ".repeat(thickness).as_str()).repeat(turns+1)); 20 | } 21 | println!("{}{}{}", ("|".to_owned() + "_".repeat(thickness*2+1).as_str()).repeat(turns / 2), (if turns % 2 == 0{"|".to_owned() + "_".repeat(thickness).as_str()} else {"|".to_owned() + "_".repeat(thickness*2+1).as_str()}), "|"); 22 | } 23 | -------------------------------------------------------------------------------- /Easy/azimut.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | fn read_string() -> String { 4 | let mut input_line = String::new(); 5 | io::stdin().read_line(&mut input_line).unwrap(); 6 | input_line.trim_matches('\n').to_string() 7 | } 8 | 9 | fn main() { 10 | 11 | let dirs = ["N", "NE", "E", "SE", "S", "SW", "W", "NW"]; 12 | let start_direction = read_string(); 13 | let mut idx = dirs.iter() 14 | .position(|&dir| dir == start_direction) 15 | .expect("Invalid direction"); 16 | 17 | for _ in 0..read_string().parse::().unwrap() { 18 | match read_string().as_str() { 19 | "RIGHT" => idx += 1, 20 | "LEFT" => idx += 7, 21 | "BACK" => idx += 4, 22 | _ => (), 23 | }; 24 | } 25 | 26 | println!("{}", dirs[idx % 8]); 27 | } 28 | -------------------------------------------------------------------------------- /Easy/balanced-ternary-computer-encode.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | void append(char* s, char c) { 7 | int len = strlen(s); 8 | s[len] = c; 9 | s[len+1] = '\0'; 10 | } 11 | 12 | char* reverse(char* s) { 13 | int len = strlen(s); 14 | char l_out[len]; 15 | 16 | for (int i = 0; i < len; ++i) l_out[i] = s[len - 1 - i]; 17 | l_out[len] = '\0'; 18 | strncpy(s, l_out, sizeof(l_out)); 19 | } 20 | 21 | void negate(char* s) { 22 | for (int i = 0; i < strlen(s); ++i) 23 | if (s[i] == '1') s[i] = 'T'; 24 | else if (s[i] == 'T') s[i] = '1'; 25 | } 26 | 27 | int main() 28 | { 29 | int N; 30 | bool negativ(false); 31 | char l_return[10] = ""; 32 | scanf("%d", &N); 33 | 34 | if (N == 0) append(l_return, '0'); 35 | else { 36 | if (N < 0) { negativ = true; N = -N; } 37 | while( N != 0) 38 | { 39 | int rest = N % 3; 40 | 41 | if (rest == 0) append(l_return, '0'); 42 | else if(rest == 1) append(l_return, '1'); 43 | else { 44 | append(l_return, 'T'); 45 | N++; 46 | } 47 | N /= 3; 48 | } 49 | if (negativ) negate(l_return); 50 | } 51 | 52 | printf("%s\n", reverse(l_return) ); 53 | 54 | return 0; 55 | } -------------------------------------------------------------------------------- /Easy/bank-robbers.js: -------------------------------------------------------------------------------- 1 | const R = parseInt(readline()); 2 | const V = parseInt(readline()); 3 | const robbers = Array.from({ length: R }).fill(0); 4 | 5 | for (let i = 0; i < V; ++i) { 6 | const inputs = readline().split(' '); 7 | const C = parseInt(inputs[0]); 8 | const N = parseInt(inputs[1]); 9 | const time = Math.pow(10, N) * Math.pow(5, C - N); 10 | robbers.sort((a, b) => a - b); 11 | robbers[0] += time; 12 | } 13 | print(Math.max(...robbers)); -------------------------------------------------------------------------------- /Easy/benfords-law.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | int N; /*!< Total number of transactions */ 6 | string tr; /*!< transaction string */ 7 | vector nbs(9,0); /*!< Number of tr starting with digit i */ 8 | vector law = 9 | { 30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6 }; 10 | 11 | cin >> N; cin.ignore(); 12 | 13 | for ( int i = 0; i < N; i++ ) 14 | { 15 | getline(cin, tr); 16 | std::size_t pos = tr.find_first_of("123456789"); 17 | ++nbs[ tr[pos] - '0' - 1 ]; 18 | } 19 | 20 | string l_ret("false"); 21 | for ( auto& nb : nbs ) 22 | { 23 | nb /= 0.01*N; 24 | nb = abs(nb - law[&nb - &nbs[0]]); 25 | 26 | if ( nb > 10 ) { l_ret = "true"; break; } 27 | } 28 | cout << l_ret << endl; 29 | } -------------------------------------------------------------------------------- /Easy/bijective-numeration.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | fn read_string() -> String { 4 | let mut input_line = String::new(); 5 | io::stdin().read_line(&mut input_line).unwrap(); 6 | input_line.trim_matches('\n').to_string() 7 | } 8 | 9 | fn to_decimal(str: &str) -> u32 { 10 | str.chars() 11 | .map(|c| match c { 12 | '1'..='9' => c.to_digit(10).unwrap(), 13 | 'A' => 10, 14 | _ => panic!("Invalid decimary symbol '{}'", c), 15 | }) 16 | .fold(0, |acc, digit| acc * 10 + digit) 17 | } 18 | 19 | fn to_decimary(mut decimal: u32) -> String { 20 | let mut res = String::new(); 21 | let mut digit: u32; 22 | while decimal > 0 { 23 | match decimal % 10 { 24 | 0 => { 25 | res.push('A'); 26 | digit = 10; 27 | }, 28 | d => { 29 | res.push(char::from_digit(d, 10).unwrap()); 30 | digit = d; 31 | }, 32 | }; 33 | decimal = (decimal - digit) / 10; 34 | } 35 | res.chars().rev().collect() 36 | } 37 | fn main() { 38 | let _ = read_string(); 39 | println!("{}", to_decimary(read_string().split_whitespace().map(to_decimal).sum::())); 40 | } 41 | -------------------------------------------------------------------------------- /Easy/binary-image.py: -------------------------------------------------------------------------------- 1 | g = [] 2 | for _ in range(int(input())): 3 | g.append(''.join('.O'[i%2]*c for i,c in enumerate(map(int, input().split())))) 4 | print('\n'.join(g) if all(len(l) == len(g[0]) for l in g) else 'INVALID' ) 5 | -------------------------------------------------------------------------------- /Easy/blackjack-solver.py: -------------------------------------------------------------------------------- 1 | points = { 'J':10, 'Q':10, 'K':10, 'A':0 } 2 | 3 | def value_cards(cards): 4 | res=0 5 | for c in cards: 6 | if c.isdigit(): res += int(c) 7 | else: res += points[c] 8 | for c in cards: 9 | if c=='A': 10 | if res > 10: res += 1 11 | else: res += 11 12 | return res 13 | 14 | bank=input().split() 15 | bc=value_cards(bank) 16 | hand=input().split() 17 | hc=value_cards(hand) 18 | 19 | if ((hc21) and bc<=21) or (hc==bc==21 and len(hand)>2 and len(bank)==2) : print('Bank') 20 | elif hc==21 and len(hand)==2 and (bc!=21 or len(bank)>2): print('Blackjack!') 21 | elif hc==bc: print('Draw') 22 | else: print('Player') 23 | -------------------------------------------------------------------------------- /Easy/blowing-fuse.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() { 4 | int n, m, c, pw=0, maxPw=0, conso[100], seq[100]; scanf("%d%d%d", &n, &m, &c); 5 | for (int i = 0; i < n; i++) { scanf("%d", &conso[i]); } 6 | for (int i = 0; i < m; i++) { 7 | scanf("%d", &seq[i] ); 8 | pw += conso[seq[i]-1]; 9 | conso[seq[i]-1] *=-1; 10 | if ( pw > maxPw ) maxPw = pw; 11 | } 12 | 13 | printf("Fuse was %sblown.\n", (maxPw > c)? "" : "not "); 14 | if ( !(maxPw > c) ) printf("Maximal consumed current was %d A.\n", maxPw); 15 | } -------------------------------------------------------------------------------- /Easy/brackets-extreme-edition.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct l_list { 4 | char data; 5 | struct l_list *next; 6 | }; 7 | 8 | void push(struct l_list** ref, int new_data) { 9 | struct l_list* l_new = (struct l_list*) malloc(sizeof(struct l_list)); 10 | l_new->data = new_data; 11 | l_new->next = *ref; 12 | *ref = l_new; 13 | } 14 | 15 | char pop(struct l_list** ref) { 16 | struct l_list *top = *ref; 17 | char result = top->data; 18 | *ref = top->next; 19 | free(top); 20 | return result; 21 | } 22 | 23 | int matching(const char c1, const char c2) { 24 | return ( (c1 == '{' && c2 == '}') || (c1 == '[' && c2 == ']') || (c1 == '(' && c2 == ')') ); 25 | } 26 | 27 | void main() { 28 | struct sNode *stack = NULL; 29 | char e[2049]; 30 | scanf("%s", e); 31 | 32 | for (int i = 0; i < strlen(e); ++i) 33 | if (e[i] == '{' || e[i] == '(' || e[i] == '[') push(&stack, e[i]); 34 | else if (e[i] == '}' || e[i] == ')' || e[i] == ']') 35 | if ( ( stack == NULL ) || ( !matching(pop(&stack), e[i]) ) ) { printf("false\n"); return; } 36 | printf("%s", (stack == NULL) ? "true\n" : "false\n"); 37 | } -------------------------------------------------------------------------------- /Easy/brick-in-the-wall.c: -------------------------------------------------------------------------------- 1 | #include 2 | int fcomp(int *w_1, int* w_2) { return *w_2 - *w_1; } 3 | 4 | void main() { 5 | int X, N; scanf("%d%d", &X, &N); 6 | float result = 0; 7 | int weights[N]; 8 | 9 | for (int i = 0; i < N; i++) scanf("%d", &weights[i]); 10 | qsort(weights, N, sizeof(*weights), fcomp); 11 | 12 | for (int i = 0; i < N; i++) result += (i/X) * weights[i]; 13 | printf("%.3f\n", 0.65*result); 14 | } -------------------------------------------------------------------------------- /Easy/builk-email-generator.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | cmpt = -1 4 | def choiceReplace(match): 5 | global cmpt 6 | cmpt += 1 7 | l_tmp = match.group()[1:-1].split('|') 8 | return l_tmp[cmpt % len(l_tmp)] 9 | 10 | N = int(input()) 11 | lines = [''] * N 12 | 13 | for i in range(N): lines[i] = input() 14 | template = '\n'.join(lines) 15 | 16 | out = re.sub('\([^)]*\)', choiceReplace, template) 17 | print(out) 18 | -------------------------------------------------------------------------------- /Easy/buzzle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int sum_of_digits(int n, int base = 10) { 4 | int ret{ 0 }; 5 | 6 | while ( 0 != n ) { ret += n % base; n /= base; } 7 | return ret; 8 | } 9 | 10 | bool buzzle(int num, int base, const std::vector& tests ) { 11 | for ( const auto& i : tests ) 12 | if ( (0 == num % i) || (i == num % base) ) return true; 13 | return ( num < base ) ? false : buzzle( sum_of_digits(num, base), base, tests ); 14 | } 15 | 16 | int main() 17 | { 18 | int base, a, b; 19 | std::cin >> base >> a >> b; std::cin.ignore(); 20 | 21 | std::vector tests{ ++std::istream_iterator(std::cin), 22 | std::istream_iterator() }; 23 | 24 | for ( auto num = a; num <= b; ++num ) { 25 | std::cerr << "num : " << num << '\n'; 26 | std::cout << ( buzzle(num, base, tests) ? "Buzzle" : std::to_string(num) ) << '\n'; 27 | } 28 | } -------------------------------------------------------------------------------- /Easy/caesar-is-the-chief.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main () { 4 | std::string buffer, wrd{}; 5 | std::getline(std::cin, buffer); 6 | 7 | for ( int i=0; i<26; ++i ) { 8 | auto decoded{ buffer }; 9 | std::transform(std::begin(buffer), std::end(buffer), std::begin(decoded), 10 | [&](char c){ return !isupper(c) ? c : char((c + i) % 26 + 'A'); }); 11 | 12 | std::istringstream ss(decoded); 13 | while (std::getline(ss, wrd, ' ')) 14 | if ( wrd == "CHIEF" ) { std::cout << decoded << "\n"; exit(EXIT_SUCCESS); } 15 | } 16 | std::cout << "WRONG MESSAGE\n"; 17 | } -------------------------------------------------------------------------------- /Easy/card-counting-when-easily-distracted.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int doTheJob(const std::string& s, int threshold) noexcept { 4 | 5 | static const std::map values{ 6 | { 'K', 10 }, { 'Q', 10 }, { 'J', 10 }, { 'T', 10 }, 7 | { '9', 9 }, { '8', 8 }, { '7', 7 }, { '6', 6 }, 8 | { '5', 5 }, { '4', 4 }, { '3', 3 }, { '2', 2 }, { 'A', 1 } 9 | }; 10 | 11 | static const std::regex rgx("^([2-9]|K|Q|J|T|A)+$", 12 | std::regex_constants::ECMAScript); 13 | 14 | int cardsLeft{ 52 }; 15 | std::map deck{ {10, 16} }; 16 | for ( auto i{1}; i < 10; ++i ) deck[i] = 4; 17 | 18 | std::string tkn; 19 | std::istringstream iss{ s }; 20 | while ( std::getline(iss, tkn, '.') ) { 21 | if ( !std::regex_search(tkn, rgx) ) continue; 22 | 23 | for ( const auto& c : tkn ) { --deck[ values.at(c) ]; } 24 | cardsLeft -= std::size(tkn); 25 | } 26 | 27 | int cnt{ 0 }; 28 | for ( const auto& [val, nb]: deck ) 29 | if ( val < threshold ) { cnt += nb; } 30 | 31 | return std::round(cnt * 100.0 / cardsLeft); 32 | } 33 | 34 | int main() 35 | { 36 | std::string SoC; 37 | int thsh; 38 | 39 | getline(std::cin, SoC); 40 | std::cin >> thsh; 41 | 42 | std::cout << doTheJob(SoC, thsh) << "%\n"; 43 | } -------------------------------------------------------------------------------- /Easy/code-breaker-puzzle.py: -------------------------------------------------------------------------------- 1 | alpha = input() 2 | msg = input() 3 | word = input() 4 | L = len(alpha) 5 | 6 | for a in range(L): 7 | for b in range(L): 8 | ret = "" 9 | for m in msg: 10 | ret += alpha[((alpha.find(m)+a)*b)%L] 11 | 12 | if word in ret: 13 | print(ret) 14 | exit(0) -------------------------------------------------------------------------------- /Easy/container-terminal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int 4 | main() 5 | { 6 | int N; 7 | std::string ships; 8 | std::cin >> N; 9 | std::cin.ignore(); 10 | 11 | while (N--) { 12 | getline(std::cin, ships); 13 | std::vector> stacks{}; 14 | 15 | std::for_each( 16 | std::begin(ships), std::end(ships), [&stacks](const auto& c) { 17 | if (auto l_stack = 18 | std::find_if(std::begin(stacks), 19 | std::end(stacks), 20 | [&](auto& st) { return c <= st.top(); }); 21 | std::end(stacks) != l_stack) { 22 | l_stack->push(c); 23 | } else { 24 | stacks.emplace_back(std::stack({ c })); 25 | } 26 | }); 27 | std::cout << std::size(stacks) << "\n"; 28 | } 29 | } -------------------------------------------------------------------------------- /Easy/cosmic-love.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Planet { 4 | std::string name; 5 | double radius, mass, dist, density; 6 | 7 | friend std::istream& operator>>(std::istream& ss, Planet& pl) { 8 | std::string rad, mass, dist; 9 | ss >> pl.name >> rad >> mass >> dist; ss.ignore(); 10 | pl.radius = atof(rad .c_str()); 11 | pl.mass = atof(mass.c_str()); 12 | pl.dist = atof(dist.c_str()); 13 | pl.density = pl.mass / ( 4*M_PI*pow(pl.radius, 3)/3 ); 14 | return ss; 15 | } 16 | 17 | friend bool operator<(const Planet& p1, const Planet& p2) { return p1.dist < p2.dist; } 18 | }; 19 | 20 | int main() 21 | { 22 | int N; 23 | std::cin >> N; std::cin.ignore(); 24 | 25 | std::vector planets(N); 26 | for ( auto& planet : planets ) std::cin >> planet; 27 | 28 | std::sort( std::begin(planets), std::end(planets) ); 29 | std::cout << (std::find_if( std::begin(planets), std::end(planets), 30 | [a = planets.front()](const auto& p){ 31 | return a.radius * pow(2 * a.density/p.density, 1/3.0) < p.dist; } ))->name << "\n"; 32 | } -------------------------------------------------------------------------------- /Easy/count-as-i-count.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | vector shots = vector(4,0); 10 | int n, res = 0; 11 | 12 | cin >> n; cin.ignore(); 13 | 14 | while ( shots[3] < 13 ) 15 | { 16 | for ( int i = 0; i < 3; i++ ) 17 | if ( shots[i] > 12 ) { shots[i] = 1; ++shots[i+1]; } 18 | 19 | if ( accumulate(shots.begin(), shots.end(), 0) == (50 - n) ) 20 | { 21 | int ways = 1; 22 | for ( auto& it : shots ) 23 | if ( it > 1 ) { ways *= 2; } 24 | 25 | res += ways; 26 | } 27 | 28 | ++shots[0]; 29 | } 30 | 31 | cout << res << endl; 32 | } 33 | 34 | /* 35 | * Dynamic programming solution if we are not limited at 4 shots 36 | */ 37 | /* 38 | int n; cin >> n; cin.ignore(); 39 | vector res = vector(51,0); 40 | res[50] = 1; 41 | 42 | for ( int i = 49; i >= n; i-- ) 43 | { 44 | res[i] = res[i+1]; 45 | 46 | int tmp = 0; 47 | for ( int j = 2; j < 13; j++ ) 48 | { 49 | if ( i + j > 50 ) { break; } 50 | tmp += res[i+j]; 51 | } 52 | 53 | res[i] += 2 * tmp; 54 | } 55 | cout << res[n] << endl; 56 | */ -------------------------------------------------------------------------------- /Easy/count-your-coins.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct CoinEntry { int val, nb; }; 4 | 5 | int main() 6 | { 7 | int goal, nbTypes; 8 | std::cin >> goal >> nbTypes; std::cin.ignore(); 9 | 10 | std::vector vData(nbTypes); 11 | for ( int i{ 0 }; i < nbTypes; ++i ) std::cin >> vData[i].nb; 12 | for ( int i{ 0 }; i < nbTypes; ++i ) std::cin >> vData[i].val; 13 | 14 | std::sort( std::begin(vData), 15 | std::end(vData), 16 | [](const auto& a, const auto& b){return a.val < b.val; }); 17 | 18 | int idx{ -1 }, ret{ 0 }; 19 | while ( goal > 0 && ++idx < nbTypes ) { 20 | auto& cEntry{ vData[idx] }; 21 | goal -= cEntry.nb * cEntry.val; 22 | ret += ( 0 >= goal ) ? cEntry.nb - abs(goal) / cEntry.val : cEntry.nb; 23 | } 24 | 25 | std::cout << ((goal > 0) ? -1 : ret) << std::endl; 26 | } -------------------------------------------------------------------------------- /Easy/crazy-list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MOD 3 4 | #define PRV(i,j) ( ((i-j) % MOD + MOD) % MOD ) 5 | 6 | int main() { 7 | 8 | std::array in; 9 | long int idx{ 0 }, cmpt{ 0 }; 10 | 11 | while ( std::cin >> in[idx] ) { cmpt++; idx = (idx + 1) % 3; } 12 | 13 | if ( 1 >= cmpt ) 14 | return EXIT_FAILURE; 15 | 16 | long int ret{ in[0] }, x{ in[PRV(idx, 3)] }, y{ in[PRV(idx, 2)] }, z{ in[PRV(idx, 1)] }; 17 | 18 | if ( y != x ) { 19 | long int A{ ( (z - y) / (y - x) ) }, B{ y - A * x }; 20 | ret = z * A + B; 21 | } 22 | 23 | std::cout << ret << std::endl; 24 | } -------------------------------------------------------------------------------- /Easy/create-the-longest-sequence-of-1s.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | char b[1000]; 7 | 8 | bool stop (int pos) { return ( (pos >= strlen(b) || pos < 0) || (b[pos] == '0') ); } 9 | int seq (int pos) { return (1 + left(pos-1) + right(pos+1) ); } 10 | int left (int p) { return ( stop(p) ? 0 : (1 + left (p-1)) ); } 11 | int right (int p) { return ( stop(p) ? 0 : (1 + right(p+1)) ); } 12 | 13 | main() 14 | { 15 | fgets(b, 1000, stdin); 16 | int l_tmp = 0, l_res = 1; 17 | char l_swap; 18 | 19 | for ( int i = 0; i < strlen(b); i++ ) 20 | { 21 | l_swap = b[i]; 22 | b[i] = '1'; 23 | l_tmp = seq(i); 24 | b[i] = l_swap; 25 | if ( l_tmp > l_res ) { l_res = l_tmp; } 26 | } 27 | printf("%d\n", l_res); 28 | } -------------------------------------------------------------------------------- /Easy/credit-card-verifier-luhns-algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | main() { 7 | int n; cin >> n; cin.ignore(); 8 | for (int i = 0; i < n; i++) { 9 | string card; getline(cin, card); 10 | int res(0); 11 | card.erase(remove(card.begin(), card.end(), ' '), card.end()); 12 | for ( int j = 0; j <= 15; j++ ) { 13 | int tmp = 2 * ( card[j] - '0' ); 14 | if (j%2==0) { res += ( tmp > 9 ) ? tmp - 9 : tmp; } 15 | else { res += card[j] - '0'; } 16 | } 17 | cout << ( (res % 10 == 0) ? "YES" : "NO" ) << endl; 18 | } 19 | } -------------------------------------------------------------------------------- /Easy/darts.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | typedef struct score { 10 | string name; 11 | int sc; 12 | int pos; 13 | 14 | score(const string& p_name = "", const int p_sc = 0, const int p = 0): name(p_name), sc(p_sc), pos(p) {}; 15 | } score; 16 | 17 | bool sortbyPlayers( const score& a, const score& b ) { 18 | if ( a.sc == b.sc ) return (a.pos < b.pos); 19 | else return (a.sc > b.sc ); 20 | } 21 | 22 | main() { 23 | int w, N, T, x, y; 24 | vector< score > v; 25 | cin >> w >> N; cin.ignore(); 26 | 27 | for (int i = 0; i < N; i++) { string name; getline(cin, name); v.push_back(score(name,0,i)); } 28 | 29 | cin >> T; cin.ignore(); 30 | for (int i = 0; i < T; i++) { 31 | string throwName; cin >> throwName >> x >> y; cin.ignore(); 32 | auto it = find_if(v.begin(), v.end(), [&throwName](const score& obj) {return obj.name == throwName;} ); 33 | if ( (abs(x) <= w/2) && (abs(y) <= w/2) ) 34 | if ( abs(x)+abs(y) <= w/2 ) { it->sc += 15; } 35 | else if ( sqrt( x*x + y*y ) <= w/2 ) { it->sc += 10; } 36 | else { it->sc += 5; } 37 | } 38 | sort(v.begin(), v.end(), sortbyPlayers); 39 | for (auto const& i : v ) cout << i.name << " " << i.sc << endl; 40 | } -------------------------------------------------------------------------------- /Easy/dead-mens-shot.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int nb_corners, nb_shots; 4 | 5 | typedef struct Point { 6 | int x; 7 | int y; 8 | }; 9 | 10 | void check( struct Point* p_shot, struct Point p_array[]) { 11 | int pos = 0; int neg = 0; int cross_prod = 0; 12 | for ( int i = 0; i < nb_corners; ++i ) { 13 | if ( (p_array[i].x == p_shot->x) && (p_array[i].y == p_shot->y) ) { printf("hit\n"); return; } 14 | 15 | int j = (i < nb_corners - 1) ? (i + 1) : 0; 16 | cross_prod = (p_shot->x - p_array[i].x) * (p_array[j].y - p_array[i].y) - (p_shot->y -p_array[i].y) * (p_array[j].x - p_array[i].x); 17 | (cross_prod > 0) ? pos++ : neg++; 18 | 19 | if ( pos && neg ) { printf("miss\n"); return; } 20 | } 21 | printf("hit\n"); return; 22 | } 23 | 24 | void main() { 25 | scanf("%d", &nb_corners); 26 | struct Point corners[nb_corners]; 27 | struct Point shot; 28 | for (int i = 0; i < nb_corners; i++) { scanf("%d %d", &corners[i].x, &corners[i].y); } 29 | 30 | scanf("%d", &nb_shots); 31 | for (int i = 0; i < nb_shots; i++) { scanf("%d %d", &shot.x, &shot.y); check(&shot, corners); } 32 | } -------------------------------------------------------------------------------- /Easy/decode-the-message.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | long long P; std::cin >> P; std::cin.ignore(); 5 | std::string C, res; std::getline(std::cin, C); 6 | 7 | while ( P >= 0 ) { res += C[ P % C.size() ]; P = P / C.size() - 1; } 8 | 9 | std::cout << res << std::endl; 10 | } -------------------------------------------------------------------------------- /Easy/detective-geek.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | fn read_string() -> String { 4 | let mut input_line = String::new(); 5 | io::stdin().read_line(&mut input_line).unwrap(); 6 | input_line.trim_matches('\n').to_string() 7 | } 8 | 9 | fn main() { 10 | let months = ["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]; 11 | 12 | let time = read_string().chars().map(|c| { 13 | match c { 14 | '#' => 1, 15 | _ => 0, 16 | } 17 | }).fold(0, |acc, x| 2 * acc + x); 18 | 19 | let mut addr = String::new(); 20 | for word in read_string().split_whitespace() { 21 | let (a, b) = word.split_at(word.len() / 2); 22 | 23 | addr.push(char::from(u8::from_str_radix(format!("{}{}", 24 | char::from_digit(months.iter().position(|&x| x == a).unwrap() as u32, 12).unwrap(), 25 | char::from_digit(months.iter().position(|&x| x == b).unwrap() as u32, 12).unwrap()).as_str(), 12).unwrap())); 26 | }; 27 | 28 | println!("{:02}:{:02}\n{}", time/100, time % 100, addr); 29 | } 30 | -------------------------------------------------------------------------------- /Easy/detective-pikaptcha-ep1.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | main() 6 | { 7 | int w, h; scanf("%d%d", &w, &h); 8 | char line[101][101]; 9 | 10 | for (int i = 0; i < h; i++) {scanf("%s", line[i]); } 11 | for (int i = 0; i < h; i++) { 12 | for (int j = 0; j < w; j++) { 13 | if (line[i][j] != '#') { 14 | if( i > 0 && line[i-1][j ] != '#' ) { line[i][j]++; } 15 | if( i < h-1 && line[i+1][j ] != '#' ) { line[i][j]++; } 16 | if( j > 0 && line[i ][j-1] != '#' ) { line[i][j]++; } 17 | if( j < w-1 && line[i ][j+1] != '#' ) { line[i][j]++; } 18 | } 19 | } 20 | printf("%s\n", line[i]); 21 | } 22 | } -------------------------------------------------------------------------------- /Easy/deus-hex-machina.py: -------------------------------------------------------------------------------- 1 | # Based on MJZ solution 2 | 3 | n = input() 4 | b = bin(int(n, 16))[2:] 5 | if b.count('0') % 2: n = n.translate(str.maketrans("2345679abcdef", "5##2a#e6d#b9#"))[::-1] 6 | if b.count('1') % 2: n = n.translate(str.maketrans("2345679abcdef", "53#2e#a9#c#6#")) 7 | 8 | print('Not a number' if '#' in n else n[:1000]) -------------------------------------------------------------------------------- /Easy/dice-handedness.py: -------------------------------------------------------------------------------- 1 | key = int(input().strip()) 2 | vals = { 1: '23', 2: '31', 3: '12', 4: '21', 5: '13', 6: '32' } 3 | str = input() 4 | s = [int(i) for i in str] 5 | 6 | print('degenerate' if s[0]+s[2] != 7 or s[1]+s[3] != 7 else 'right-handed' if vals[key] in str*2 else 'left-handed') 7 | -------------------------------------------------------------------------------- /Easy/distributing-candy.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n, m, ret{ std::numeric_limits::max() }; 6 | std::cin >> n >> m; std::cin.ignore(); 7 | 8 | std::vector bags{ std::istream_iterator(std::cin), 9 | std::istream_iterator() }; 10 | std::sort( std::begin(bags), std::end(bags) ); 11 | 12 | for ( int i = 0; i <= n - m; ++i ) 13 | ret = std::min( ret, bags[i + m - 1] - bags[i] ); 14 | 15 | std::cout << ret << '\n'; 16 | } -------------------------------------------------------------------------------- /Easy/dolbears-law.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | using namespace std; 11 | 12 | int main() 13 | { 14 | string line; 15 | int M; cin >> M; cin.ignore(); 16 | vector temps; 17 | float N60_mean = 0.f, N8_mean = 0.f; 18 | 19 | for (int i = 0; i < M; i++) 20 | { 21 | getline(cin, line); 22 | istringstream iss(line); 23 | for(string s; iss >> s; ) 24 | { 25 | temps.push_back(stoi(s)); 26 | } 27 | } 28 | 29 | int i = 0; 30 | do { 31 | auto it = temps.begin() + i; 32 | N60_mean += 10 + (accumulate( it, it + 15, 0) - 40)/7.f; 33 | i += 15; 34 | } while( i + 15 <= temps.size() ); 35 | 36 | i = 0; 37 | int j = 0; 38 | do { 39 | j++; 40 | auto it = temps.begin() + i; 41 | N8_mean += 5 + accumulate( it, it + 2, 0); 42 | i += 2; 43 | } while( i + 2 <= temps.size() ); 44 | 45 | N60_mean/=M; 46 | N8_mean /=j; 47 | 48 | cout << fixed << setprecision(1) << (float)N60_mean << endl; 49 | if( N60_mean >= 5 && N60_mean <= 30 ) 50 | { 51 | cout << fixed << setprecision(1) << N8_mean << endl; 52 | } 53 | } -------------------------------------------------------------------------------- /Easy/duo-combinations.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | use std::collections::HashSet; 3 | 4 | macro_rules! parse_input { 5 | ($t:ident) => {{ 6 | let mut input_line = String::new(); 7 | io::stdin().read_line(&mut input_line).unwrap(); 8 | input_line.trim_matches('\n').parse::<$t>().unwrap() 9 | }} 10 | } 11 | 12 | fn main() { 13 | let mut cache = HashSet::new(); 14 | let total = parse_input!(usize); 15 | let mut alphabet = Vec::new(); 16 | alphabet.reserve(total); 17 | 18 | for _ in 0..total { 19 | alphabet.push(parse_input!(String)); 20 | } 21 | 22 | let seq: Vec = (0..(1 << total)) 23 | .map(|number| format!("{:0total$b}", number)) 24 | .collect(); 25 | 26 | for (a, b) in alphabet.iter().zip(alphabet.iter().skip(1)) { 27 | for bin in &seq { 28 | let entry = bin.replace('0', a).replace('1', b); 29 | if !cache.contains(&entry) { 30 | cache.insert(entry.clone()); 31 | println!("{entry}"); 32 | } 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /Easy/egyptian-multiplication.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | macro_rules! parse_input { 4 | ($t:ident) => {{ 5 | let mut input_line = String::new(); 6 | io::stdin().read_line(&mut input_line).unwrap(); 7 | input_line.trim_matches('\n').parse::<$t>().unwrap() 8 | }} 9 | } 10 | 11 | fn main() { 12 | let inputs = parse_input!(String) 13 | .split(' ') 14 | .map(|x| x.parse::().unwrap_or(0)) 15 | .collect::>(); 16 | 17 | let mut b = core::cmp::min(inputs[0], inputs[1]); 18 | let mut a = core::cmp::max(inputs[0], inputs[1]); 19 | 20 | let mut decomp = Vec::new(); 21 | 22 | println!("{} * {}", a, b); 23 | 24 | while 0 != b { 25 | match b % 2 { 26 | 0 => { 27 | a = a * 2; 28 | b = (b + 1)/2; 29 | }, 30 | _ => { 31 | decomp.push(a); 32 | b = b - 1; 33 | }, 34 | } 35 | let decomp_str = if decomp.is_empty() { 36 | String::new() 37 | } else { 38 | format!(" + {}", decomp.iter() 39 | .map(ToString::to_string) 40 | .collect::>() 41 | .join(" + ")) 42 | }; 43 | 44 | println!("= {} * {}{}", a, b, decomp_str); 45 | } 46 | println!("= {}", decomp.iter().sum::()); 47 | } 48 | -------------------------------------------------------------------------------- /Easy/embedded-chessboards.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Painting { 4 | int row, col, isWhite; 5 | friend std::istream& operator>>(std::istream& is, Painting& p) noexcept { 6 | return is >> p.row >> p.col >> p.isWhite; 7 | } 8 | }; 9 | 10 | int main() 11 | { 12 | std::cin.ignore(std::numeric_limits::max(), '\n'); 13 | Painting P; 14 | for(; std::cin >> P;) 15 | std::cout << (P.row < 8 || P.col < 8 ? 0 : 16 | ((P.row - 7) * (P.col - 7) + P.isWhite)/2) << '\n'; 17 | } -------------------------------------------------------------------------------- /Easy/encryptiondecryption-of-enigma-machine.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | main() { 5 | char op[257]; fgets(op, 257, stdin); 6 | int num; scanf("%d", &num); fgetc(stdin); 7 | char rot[3][27]; 8 | char mesg[1025]; 9 | 10 | for (int i = 0; i < 3; i++) { fgets(rot[i], 27, stdin); fgetc(stdin); } 11 | fgets(mesg, 1025, stdin); 12 | 13 | if (op[0] == 'E') { 14 | for (int i = 0; i < strlen(mesg); i++) { mesg[i] = ((mesg[i] -'A' + num + i ) % 26)+'A'; } 15 | for (int i = 0; i < 3; i++) for(int j = 0; j < strlen(mesg); j++) { mesg[j] = rot[i][mesg[j]-'A']; } 16 | } 17 | else if(op[0] == 'D') { 18 | for (int i = 2; i >= 0; i--) 19 | for(int j = 0; j < strlen(mesg); j++) 20 | for ( int c = 0; c < strlen(rot[i]); c++) 21 | if(rot[i][c]==mesg[j]) { mesg[j] = 'A'+c; break; } 22 | for (int i = 0; i < strlen(mesg); i++) { 23 | int idx = (mesg[i] +'A' - (num + i)); 24 | idx += (idx<0)?26:0; 25 | mesg[i] = (idx % 26)+'A'; 26 | } 27 | } 28 | printf("%s\n", mesg); 29 | } -------------------------------------------------------------------------------- /Easy/euclids-algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int gcd_steps(int a, 4 | int b) noexcept { 5 | if ( 0 == b ) 6 | return a; 7 | int aa{ a / b }, bb{ a % b }; 8 | std::cout << a << '=' << b << '*' << aa << '+' << bb << '\n'; 9 | return gcd_steps(b, bb); 10 | } 11 | 12 | int main() 13 | { 14 | int a, b; 15 | std::cin >> a >> b; 16 | 17 | auto gcd{ gcd_steps(a,b) }; 18 | std::cout << "GCD(" << a << ',' << b << ")=" << gcd << '\n'; 19 | } -------------------------------------------------------------------------------- /Easy/extended-hamming-codes.py: -------------------------------------------------------------------------------- 1 | data = list(map(int, input())) 2 | check = 0 3 | for i in range(1,16): 4 | if data[i]: check ^= i 5 | if check: data[check] ^= 1 6 | print('TWO ERRORS' if sum(data)&1 else ''.join(map(str, data))) -------------------------------------------------------------------------------- /Easy/faro-shuffle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int N, half; 5 | std::cin >> N; std::cin.ignore(); 6 | 7 | std::vector dck(std::istream_iterator {std::cin}, 8 | std::istream_iterator {}); 9 | 10 | half = std::ceil(std::size(dck) / 2.); 11 | 12 | while ( N-- ) { 13 | auto lhs = std::vector(std::begin(dck), std::begin(dck) + half); 14 | auto rhs = std::vector(std::begin(dck) + half, std::end(dck) ); 15 | 16 | auto lit{ std::begin(lhs) }, rit{ std::begin(rhs) }; 17 | for ( auto i = 0; i < std::size(dck); ++i ) 18 | dck[i] = ( 0 == i % 2 ) ? *lit++ : *rit++; 19 | } 20 | 21 | std::stringstream ss; 22 | for ( const auto& l : dck ) ss << l << " "; 23 | auto ret = ss.str(); 24 | ret.pop_back(); 25 | std::cout << ret; 26 | } -------------------------------------------------------------------------------- /Easy/fax-machine.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | std::stringstream ss; 6 | std::istream_iterator it(std::cin), eos; 7 | std::vector v (it, eos); 8 | std::string res{""}; 9 | 10 | for ( int i = 2; i < std::size(v); ++i ) 11 | res += ( i % 2 ) ? std::string(v[i],' ') : std::string(v[i],'*'); 12 | 13 | std::for_each( std::begin(res), std::end(res), [&v, &ss](auto c){ 14 | static int cmpt = 0; 15 | if ( cmpt % v[0] == 0 ) { cmpt = 0; ss << "|\n|"; } 16 | ss << c; 17 | ++cmpt; 18 | }); 19 | 20 | std::cout << ss.str().substr(2) << "|\n"; 21 | } -------------------------------------------------------------------------------- /Easy/feature-extraction.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template < typename T > 4 | using V = std::vector; 5 | 6 | int convAt( const V< V >& img, 7 | const V< V >& krnl, 8 | const std::pair& pos) { 9 | int ret{0}; 10 | 11 | for ( int i = 0; i < std::size(krnl[0]); ++i ) { 12 | for ( int j = 0; j < std::size(krnl); ++j ) { 13 | ret += img[i + pos.first][j + pos.second] * krnl[i][j]; 14 | } 15 | } 16 | 17 | return ret; 18 | } 19 | 20 | int main() 21 | { 22 | int r, c, m, n; 23 | std::cin >> r >> c; std::cin.ignore(); 24 | 25 | V< V > img(r, V(c,0) ); 26 | for ( int i = 0; i < r; ++i ) 27 | for ( int j = 0; j < c; ++j ) { std::cin >> img[i][j]; std::cin.ignore(); } 28 | 29 | std::cin >> m >> n; std::cin.ignore(); 30 | V< V > krnl(m, V(n,0) ); 31 | for ( int i = 0; i < m; ++i ) 32 | for ( int j = 0; j < n; ++j ) { std::cin >> krnl[i][j]; std::cin.ignore(); } 33 | 34 | V< V > res(r - m, V(c - n, 0) ); 35 | for ( int i = 0; i <= r - m; ++i ) { 36 | std::string ss; 37 | for ( int j = 0; j <= c - n; ++j ) 38 | ss += std::to_string(convAt(img, krnl, {i, j})) + " "; 39 | ss.pop_back(); 40 | std::cout << ss << std::endl; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /Easy/fibonaccis-rabbit.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | fn read_line() -> (usize,usize) { 4 | let mut input_line = String::new(); 5 | io::stdin().read_line(&mut input_line).unwrap(); 6 | let inputs = input_line.trim_matches('\n').split(" ").collect::>(); 7 | (inputs[0].parse::().unwrap(), inputs[1].parse::().unwrap()) 8 | } 9 | 10 | fn main() { 11 | 12 | let (f0, n) = read_line(); 13 | let (a, b) = read_line(); 14 | 15 | let mut f: Vec:: = vec![0; b]; 16 | f.push(f0 as u64); 17 | 18 | for _ in 1..=n as usize { 19 | for prev in 0..b as usize { 20 | f[prev] = f[prev+1]; 21 | } 22 | f[b] = f[..=(b-a)].iter().sum(); 23 | } 24 | println!("{}", f[b]); 25 | } 26 | -------------------------------------------------------------------------------- /Easy/firecontrol.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define SIZE 6 4 | 5 | int main() 6 | { 7 | int fires{ 0 }, trees{ 0 }, to_cut{ 0 }; 8 | std::vector grid{ std::istream_iterator(std::cin), 9 | std::istream_iterator()}; 10 | std::set< std::pair > firesList{}; 11 | 12 | for (const auto& line : grid) 13 | std::cerr << line << '\n'; 14 | 15 | for ( int i = 0; i < SIZE; ++i ) 16 | for ( int j = 0; j < SIZE; ++j ) { 17 | if ( '*' == grid[i][j] ) ++fires, firesList.insert({i,j}); 18 | else if ( '#' == grid[i][j] ) ++trees; 19 | } 20 | 21 | if ( !fires ) { std::cout << "RELAX\n"; return EXIT_SUCCESS; } 22 | else if ( !trees ) { std::cout << "JUST RUN\n"; return EXIT_SUCCESS; } 23 | 24 | for ( const auto& f : firesList ) 25 | for ( int i = f.first - 2; i <= f.first + 2; ++i) 26 | for ( int j = f.second - 2; j <= f.second + 2; ++j) { 27 | if ( i < 0 || i >= SIZE || j < 0 || j >= SIZE ) continue; 28 | if ( auto& cell = grid[i][j]; '#' == cell ) { cell = '='; ++to_cut; } 29 | } 30 | 31 | std::cout << ( (to_cut == trees) ? "JUST RUN" : std::to_string(to_cut)) << '\n'; 32 | } -------------------------------------------------------------------------------- /Easy/fix-the-networks.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | macro_rules! parse_input { 4 | ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap()) 5 | } 6 | 7 | fn main() { 8 | let mut input = String::new(); 9 | io::stdin().read_line(&mut input).unwrap(); 10 | let m: usize = parse_input!(input, usize); 11 | 12 | for _ in 0..m { 13 | let mut input = String::new(); 14 | io::stdin().read_line(&mut input).unwrap(); 15 | let parts: Vec<&str> = input.trim().split("/").collect(); 16 | 17 | let ip = parts[0]; 18 | let cidr: u32 = parts[1].parse().unwrap(); 19 | let var_part = 32 - cidr; 20 | 21 | let ip_bins: Vec = ip.split('.') 22 | .map(|s| format!("{:08b}", s.parse::().unwrap())) 23 | .collect(); 24 | let ip_bin_str = ip_bins.join(""); 25 | 26 | if var_part == 0 { 27 | println!("valid 1"); 28 | } else { 29 | let var_part_str = &ip_bin_str[ip_bin_str.len() - var_part as usize..]; 30 | if var_part_str.chars().all(|c| c == '0') { 31 | println!("valid {}", 2u64.pow(var_part)); 32 | } else { 33 | let var_part = ip_bin_str.chars().rev().take_while(|&c| c == '0').count(); 34 | let cidr = 32 - var_part; 35 | println!("invalid {}/{} {}", ip, cidr, 2u64.pow(var_part as u32)); 36 | } 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /Easy/flip-the-sign.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | #define loop2(i,j,h,w) for(int i=0; i> h >> w; cin.ignore(); 11 | 12 | int grid_nb[h][w]; 13 | loop2(i,j,h,w) { cin >> grid_nb[i][j]; } 14 | 15 | char grid_str[h][w]; 16 | loop2(i,j,h,w) { cin >> grid_str[i][j]; } 17 | 18 | loop2(i,j,h,w) { 19 | if ( grid_str[i][j] == 'X' ) 20 | { 21 | if ( sign == 0 || sign * grid_nb[i][j] < 0 ) { sign = grid_nb[i][j]; } 22 | else { cout << "false"; return 0; } 23 | } 24 | } 25 | cout << "true" << endl; 26 | } -------------------------------------------------------------------------------- /Easy/frame-the-picture.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | std::string pattern, padding; 5 | std::getline(std::cin, pattern); 6 | 7 | auto reverse_pattern{pattern}, reverse_padding{padding}; 8 | std::reverse( std::begin(reverse_pattern), std::end(reverse_pattern)); 9 | 10 | int h, w, p(pattern.size()); 11 | std::cin >> h >> w; std::cin.ignore(); 12 | 13 | std::vector frame(h), border; 14 | for ( auto& l : frame ) { 15 | getline(std::cin, l); 16 | l.resize(w, ' '); 17 | } 18 | 19 | for ( auto i = 0; i <= p; ++i ) { 20 | auto line = std::string( w + 2 * ( 1 + p - i), i < p ? pattern[i] : ' ' ); 21 | padding = pattern.substr(0, i); 22 | reverse_padding = padding; 23 | std::reverse(std::begin(reverse_padding), std::end(reverse_padding)); 24 | line = padding + line + reverse_padding; 25 | border.insert(std::begin(border), line); 26 | 27 | std::cout << line << "\n"; 28 | } 29 | 30 | for ( auto& l : frame ) 31 | std::cout << pattern + " " + l + " " + reverse_pattern << "\n"; 32 | 33 | for ( auto& l : border ) 34 | std::cout << l << "\n"; 35 | } -------------------------------------------------------------------------------- /Easy/gdq---binary-coded-decimal-clock.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define OUT(val, shift) ( ((val >> shift) & 1U) ? "#####" : "_____" ) 4 | #define REQUIRED_SIZE 10 5 | 6 | int main() { 7 | 8 | std::string in; 9 | getline(std::cin, in); 10 | 11 | if ( REQUIRED_SIZE != std::size(in) ) 12 | return EXIT_FAILURE; 13 | 14 | int hh{ in[1] - '0'}, m1{ in[3] - '0'}, m2{ in[4] - '0'}, 15 | s1{ in[6] - '0'}, s2{ in[7] - '0'}, f { in[9] - '0'}; 16 | 17 | printf( "|%s|%s|%s|%s|%s|%s|\n" 18 | "|%s|%s|%s|%s|%s|%s|\n" 19 | "|%s|%s|%s|%s|%s|%s|\n" 20 | "|%s|%s|%s|%s|%s|%s|\n", 21 | OUT(hh,3), OUT(m1,3), OUT(m2,3), OUT(s1,3), OUT(s2,3), OUT(f,3), 22 | OUT(hh,2), OUT(m1,2), OUT(m2,2), OUT(s1,2), OUT(s2,2), OUT(f,2), 23 | OUT(hh,1), OUT(m1,1), OUT(m2,1), OUT(s1,1), OUT(s2,1), OUT(f,1), 24 | OUT(hh,0), OUT(m1,0), OUT(m2,0), OUT(s1,0), OUT(s2,0), OUT(f,0)); 25 | } -------------------------------------------------------------------------------- /Easy/genetics-and-computers---part-1.py: -------------------------------------------------------------------------------- 1 | # (nice) Solution from schachmatt 2 | 3 | import sys 4 | import math 5 | from functools import reduce 6 | 7 | p1, p2 = input().split() 8 | ratio = ["".join(sorted(s)) for s in input().split(":")] 9 | counts = {x:0 for x in ratio} 10 | 11 | a,b,c,d = p1; p1 = [a+c, a+d, b+c, b+d] 12 | a,b,c,d = p2; p2 = [a+c, a+d, b+c, b+d] 13 | 14 | for x in p1: 15 | for y in p2: 16 | z = "".join(sorted(x+y)) 17 | if z in counts: 18 | counts[z] += 1 19 | 20 | g = reduce(math.gcd, counts.values()) 21 | 22 | print(*[counts[x]//g for x in ratio], sep=":") -------------------------------------------------------------------------------- /Easy/ghost-legs.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | int W, H, curW, curH; 8 | 9 | scanf("%d%d", &W, &H); fgetc(stdin); 10 | char tab[H][W]; 11 | for (int i = 0; i < H; i++) fgets(tab[i], 1025, stdin); 12 | 13 | 14 | for( int cmpt_w = 0; cmpt_w < W; cmpt_w += 3 ) 15 | { 16 | curW = cmpt_w; 17 | curH = 0; 18 | while(curH < H-1) { 19 | curH++; 20 | fprintf(stderr, "%c\n", tab[curH][curW]); 21 | if ( tab[curH][curW] != '|' && 22 | tab[curH][curW] != ' ' && 23 | tab[curH][curW] != '-' ) { printf("%c%c\n", tab[0][cmpt_w], tab[curH][curW] ); } 24 | else if( (curW < W - 1) && (tab[curH][curW +1] == '-') ) { curW += 3; } 25 | else if( (curW > 0) && (tab[curH][curW -1] == '-') ) { curW -= 3; } 26 | } 27 | } 28 | 29 | return 0; 30 | } -------------------------------------------------------------------------------- /Easy/happy-numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void test_happy(string& p_in) 8 | { 9 | string l_tmp = p_in; 10 | set l_mem; 11 | 12 | while(l_mem.find(l_tmp) == l_mem.end() ) 13 | { 14 | l_mem.insert(l_tmp); 15 | int l_buffer = 0; 16 | 17 | for(auto& c: l_tmp) { l_buffer += (c - '0') * (c - '0'); } 18 | if (l_buffer == 1 ) { cout << p_in << " :)" << endl; return; } 19 | 20 | l_tmp = to_string(l_buffer); 21 | } 22 | cout << p_in << " :(" << endl; 23 | } 24 | 25 | main() 26 | { 27 | int N; 28 | string curr_entry; 29 | 30 | cin >> N; cin.ignore(); 31 | 32 | for (int i = 0; i < N; i++) 33 | { 34 | getline(cin, curr_entry); 35 | test_happy(curr_entry); 36 | } 37 | } -------------------------------------------------------------------------------- /Easy/hidden-messages-in-images.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | int w, h, px; 7 | std::cin >> w >> h; 8 | 9 | std::vector bytes( w*h/8, 0); 10 | for (int i = 0; i < w*h && std::cin >> px; i++) 11 | bytes[ i/8 ] |= (px & 1UL) << (7 - i%8); 12 | 13 | for ( const auto& elm : bytes ) std::cout << static_cast(elm); 14 | std::cout << std::endl; 15 | } -------------------------------------------------------------------------------- /Easy/hooch-clash.sh: -------------------------------------------------------------------------------- 1 | read sMin sMax 2 | read gS1 gS2 3 | (( V = gS1**3 + gS2**3 )) 4 | for (( i = sMin, j = sMax; i <= sMax; i++ )); do 5 | (( i == gS1 )) && continue 6 | (( j3 = V - i**3 )) 7 | (( j3 < sMin**3 )) && break 8 | (( j3 >= i**3 )) || break 9 | for (( ; j**3 > j3; j-- )); do :; done 10 | if (( j**3 == j3 )); then 11 | echo $i $j 12 | exit 13 | fi 14 | done 15 | echo VALID -------------------------------------------------------------------------------- /Easy/horse-racing-duals.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int main() 8 | { 9 | std::istream_iterator it(std::cin ), eos; 10 | std::vector in(++it, eos); 11 | 12 | std::sort ( in.begin(), in.end() ); 13 | std::adjacent_difference( in.begin(), in.end(), in.begin() ); 14 | 15 | std::cout << (*std::min_element(in.begin(), in.end())) << std::endl; 16 | } -------------------------------------------------------------------------------- /Easy/horse-racing-hyperduals.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct horse { 5 | int v, e; 6 | }; 7 | 8 | int d( const struct horse* h1, const struct horse* h2) { 9 | return ( (h1 == h2) ? 10e9 : abs(h2->v - h1->v) + abs(h2->e - h1->e) ); 10 | } 11 | 12 | main() { 13 | int N, V, E; scanf("%d", &N); 14 | int min_d = 10e9; 15 | struct horse h[N], *p = h; 16 | for (int i = 0; i < N; i++) { scanf("%d%d", &p->v, &p->e); p++; } 17 | for (int i = 0; i < N; i++) 18 | for (int j = 0; j < N; j++) 19 | min_d = (d(&h[i], &h[j]) < min_d) ? d(&h[i], &h[j]) : min_d; 20 | printf("%d\n", min_d); 21 | } -------------------------------------------------------------------------------- /Easy/how-time-flies.py: -------------------------------------------------------------------------------- 1 | # Inspired by "Zexion" solution 2 | 3 | from datetime import datetime as dt 4 | b, e = [dt.strptime(input(), '%d.%m.%Y') for _ in range(2)] 5 | 6 | d = (e - b).days 7 | m = (dt.min + (e - b)).month - 1 8 | y = d // 365 9 | 10 | if y > 0: print('%d year%s, ' % (y, 's' if y > 1 else ''), end='') 11 | if m > 0: print('%d month%s, ' % (m, 's' if m > 1 else ''), end='') 12 | print('total %d days' % d) 13 | -------------------------------------------------------------------------------- /Easy/hunger-games.py: -------------------------------------------------------------------------------- 1 | class Tribute(): 2 | def __init__(self, name): 3 | self.name = name 4 | self.killed = [] 5 | self.killer = None 6 | def setKill (self, name): self.killed.append(name) 7 | def setKiller(self, name): self.killer = name 8 | def getMesg (self): 9 | killed = "None" if len(self.killed) == 0 else ", ".join(sorted(self.killed)) 10 | killer = "Winner" if self.killer is None else self.killer 11 | return "Name: {}\nKilled: {}\nKiller: {}".format(self.name, killed, killer) 12 | 13 | tribes = int(input()) 14 | plrs = dict() 15 | for i in range(tribes): 16 | pName = input() 17 | plrs[pName] = Tribute(pName) 18 | for i in range(int(input())): 19 | s = input().split(" killed ") 20 | for victim in s[1].split(", "): 21 | plrs[s[0] ].setKill (victim) 22 | plrs[victim].setKiller(s[0]) 23 | 24 | print("\n\n".join([plrs[k].getMesg() for k in sorted(plrs.keys())])) 25 | -------------------------------------------------------------------------------- /Easy/in-stereo.py: -------------------------------------------------------------------------------- 1 | input() 2 | pt = input() 3 | input() 4 | st = input() 5 | h, _ = map(int, input().split()) 6 | for i in range(h): 7 | res = "" 8 | depth = pos = 0 9 | p, s = list(pt), list(st) 10 | for d in map(int,input()): 11 | for n in range(d - depth): 12 | del p[pos] 13 | pos = pos % len(p) 14 | for n in range(depth - d): 15 | p.insert(pos+n,s.pop(0)) 16 | res += p[pos] 17 | pos = (pos+1)%len(p) 18 | depth = d 19 | print(res) -------------------------------------------------------------------------------- /Easy/insert-to-string.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | size_t get_line_pos(const std::string& in, size_t pos, size_t lineNb) { 4 | if(0 == lineNb) return pos; 5 | return get_line_pos(in, in.find("\\n", pos) + 2, lineNb-1); 6 | } 7 | 8 | struct Commit { 9 | int line, col; 10 | std::string val; 11 | 12 | static void insert(std::string& str, const Commit& c) { 13 | str.insert(get_line_pos(str, 0, c.line) + c.col, c.val); 14 | } 15 | }; 16 | 17 | std::istream& operator>>(std::istream& is, Commit& in) { 18 | char useless; 19 | is >> in.line >> useless >> in.col >> useless; 20 | getline(std::cin, in.val); 21 | return is; 22 | } 23 | 24 | int main() 25 | { 26 | std::string s, line; getline(std::cin, s); 27 | std::cin.ignore(std::numeric_limits::max(), '\n'); 28 | 29 | std::vector< Commit > commits{ std::istream_iterator(std::cin), 30 | std::istream_iterator() }; 31 | std::sort( std::begin(commits), std::end(commits), [](const auto& a, const auto& b){ 32 | return (a.line > b.line) || ( a.line == b.line && a.col > b.col); 33 | } ); 34 | 35 | for (const auto& commit : commits ) 36 | Commit::insert(s, commit); 37 | 38 | std::cout << std::regex_replace(s, std::regex(R"(\\n)"), "\n") << '\n'; 39 | } -------------------------------------------------------------------------------- /Easy/ipv6-shortener.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import re 3 | 4 | res = ":" + input() 5 | zer = sorted(list(re.findall(":(?:0+:)+0+:",res)), key=lambda x:-1*len(x)) 6 | if (len(zer)) > 0: 7 | res = res.replace(zer[0],"::") 8 | res = re.sub(":0+",":0",res) 9 | res = re.sub(":0([1-9a-f])",":\\1",res) 10 | res = re.sub("^:::","::",res) 11 | res = re.sub("^:([^:])","\\1",res) 12 | print(res) 13 | 14 | # That would work too... 15 | # import ipaddress 16 | # print(ipaddress.IPv6Address(input())) 17 | -------------------------------------------------------------------------------- /Easy/jack-silver-the-casino.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | main() { 5 | int r, c, roulette, curr_number, bet; 6 | scanf("%d %d", &r, &c); 7 | 8 | for (int i = 0; i < r; i++) { 9 | char turn[1025]; scanf("%d %s",&roulette, turn); 10 | bet = ceil(c/4.f); 11 | c -= bet; 12 | 13 | if ( *turn == 'E' ) { 14 | if (roulette && (roulette & 1) == 0) { c += 2*bet; } } 15 | else if ( *turn == 'O' ) { 16 | if (roulette & 1) { c += 2*bet; } } 17 | else if ( *turn == 'P' ) { 18 | scanf("%d", &curr_number); 19 | if (roulette == curr_number) { c += 36*bet; } } 20 | } 21 | printf("%d\n", c); 22 | } -------------------------------------------------------------------------------- /Easy/kiss-the-girls.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | int H, W; 5 | std::cin >> H >> W; 6 | 7 | double res{ 1 }; 8 | std::vector< double > probs; 9 | std::vector< std::string > grid{ std::istream_iterator(std::cin), 10 | std::istream_iterator() }; 11 | 12 | 13 | for ( double y = 0; y < H; ++y ) 14 | for( double x = 0; x < W; ++x ) 15 | if( 'G' == grid[y][x] ) 16 | probs.push_back( std::min(x, y)/( x*x + y*y + 1) ); 17 | 18 | std::sort( std::begin(probs), std::end(probs) ); 19 | 20 | for( int i = 0; i < std::size(probs); ++i ) { 21 | res *= 1 - probs[i]; 22 | if( res < 0.6 ){ std::cout << i << '\n'; break; } 23 | } 24 | } -------------------------------------------------------------------------------- /Easy/largest-number.py: -------------------------------------------------------------------------------- 1 | number = input() 2 | D = int(input()) 3 | ret = 0 4 | 5 | def DFS(nb, depth): 6 | global ret 7 | n = int(nb) 8 | if n % D == 0 and n > ret: 9 | ret = n 10 | if depth == 2: 11 | return 12 | for i in range(len(number)-depth): 13 | DFS(nb[:i] + nb[i+1:], depth+1) 14 | 15 | DFS(number,0) 16 | print(ret) -------------------------------------------------------------------------------- /Easy/logic-gates.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef std::string SIG; 4 | 5 | int main() 6 | { 7 | int n, m; 8 | std::string so, s1, s2, op, val; 9 | 10 | std::unordered_map cache; 11 | std::unordered_map> ops = 12 | { 13 | {"AND", [](bool a, bool b){return a & b; }}, 14 | {"OR", [](bool a, bool b){return a | b; }}, 15 | {"XOR", [](bool a, bool b){return a ^ b; }}, 16 | {"NAND", [](bool a, bool b){return !(a & b); }}, 17 | {"NOR", [](bool a, bool b){return !(a | b); }}, 18 | {"NXOR", [](bool a, bool b){return !(a ^ b); }}, 19 | }; 20 | 21 | std::cin >> n >> m; 22 | for (int i = 0; i < n; ++i) 23 | std::cin >> so >> cache[so]; 24 | 25 | for (int i = 0; i < m; ++i) { 26 | std::cin >> so >> op >> s1 >> s2; 27 | std::cout << so << " "; 28 | for (int j = 0; j < cache[s1].size(); ++j) 29 | std::cout << (ops[op](cache[s1][j] == '-', cache[s2][j] == '-') ? '-' : '_'); 30 | std::cout << '\n'; 31 | } 32 | } -------------------------------------------------------------------------------- /Easy/low-resolution-whats-the-shape.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | string row; 6 | double res{0}; 7 | int W, H; cin >> W >> H; cin.ignore(); 8 | 9 | for (int i = 0; i < H && getline(cin, row); i++) 10 | for ( auto&& c : row ) 11 | if ( c != '.' ) { res += ( c == 'X' ) ? 1 : 0.5; } 12 | res /= W*H; 13 | cout << ( (res > 0.8)?"Rectangle":((res > 0.6 )?"Ellipse":"Triangle") ) << endl; 14 | } -------------------------------------------------------------------------------- /Easy/lumen.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int N, L; 6 | 7 | int getBlackSpots( const int array[][N] ) 8 | { 9 | int l_return = 0; 10 | 11 | for( int i = 0; i < N; i++ ) 12 | for( int j = 0; j < N; j++ ) 13 | l_return += ( array[i][j] == 0 ) ? 1 : 0; 14 | 15 | return l_return; 16 | } 17 | 18 | int updateOne( const int x1, const int x2, const int y1, const int y2) 19 | { 20 | int l_return = L; 21 | l_return -= ( abs(x2-x1) > abs(y2-y1) ) ? abs(x2-x1) : abs(y2-y1); 22 | 23 | return ( l_return > 0 ) ? l_return : 0; 24 | } 25 | 26 | void update( const int row, const int col, int array[][N]) 27 | { 28 | for( int i = 0; i < N; i++ ) 29 | for( int j = 0; j < N; j++ ) { 30 | int l_tmp = updateOne(row, i, col, j); 31 | array[i][j] = (l_tmp > array[i][j]) ? l_tmp : array[i][j]; 32 | } 33 | } 34 | 35 | void main() 36 | { 37 | scanf("%d%d", &N, &L); fgetc(stdin); 38 | int square[N][N]; memset( square, 0, N * N * sizeof(int) ); 39 | 40 | for ( int i = 0; i < N; i++ ) { 41 | char LINE[501]; fgets(LINE, 501, stdin); 42 | for ( int j = 0; j < strlen(LINE); ++j ) if ( LINE[j] == 'C' ) update ( i, j/2, square ); 43 | } 44 | 45 | printf("%d\n", getBlackSpots(square) ); 46 | } -------------------------------------------------------------------------------- /Easy/mandelbrot-set-approximation.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | macro_rules! parse_input { 4 | ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap()) 5 | } 6 | 7 | fn main() { 8 | let mut input_line = String::new(); 9 | io::stdin().read_line(&mut input_line).unwrap(); 10 | 11 | let ny = parse_input!(input_line, i32); 12 | let nx: i32 = 3 * (ny - 1) / 2 + 1; 13 | 14 | let dy: f64 = 2.0 / (ny - 1) as f64; 15 | let dx: f64 = 3.0 / (nx - 1) as f64; 16 | 17 | let y: Vec = (0..ny).map(|i| 1.0 - (i as f64 * dy)).collect(); 18 | let x: Vec = (0..nx).map(|i| -2.0 + (i as f64 * dx)).collect(); 19 | 20 | let f = |cr: f64, ci: f64| -> char { 21 | let mut zr = 0.0; 22 | let mut zi = 0.0; 23 | 24 | for _ in 0..10 { 25 | let zr_new = zr * zr - zi * zi + cr; 26 | let zi_new = 2.0 * zr * zi + ci; 27 | zr = zr_new; 28 | zi = zi_new; 29 | } 30 | 31 | if (zr * zr + zi * zi).sqrt() <= 1.0 { '*' } else { ' ' } 32 | }; 33 | 34 | for yi in y { 35 | let line: String = x.iter() 36 | .map(|&xi| f(xi, yi)) 37 | .collect(); 38 | println!("{}", line); 39 | } 40 | } -------------------------------------------------------------------------------- /Easy/mars-lander-episode-1.py: -------------------------------------------------------------------------------- 1 | while True: print("0 3\n0 4") -------------------------------------------------------------------------------- /Easy/match-dna-sequence.rs: -------------------------------------------------------------------------------- 1 | use std::io::*; 2 | 3 | fn diff(src: &str, tgt: &str, max_delta: usize) -> usize { 4 | let mut d = 0; 5 | if tgt.len() < src.len() { 6 | d = src.len() - tgt.len(); 7 | } 8 | 9 | for (c1, c2) in src.chars().zip( tgt.chars() ) { 10 | if c1 != c2 { 11 | d += 1; 12 | } 13 | 14 | if d > max_delta { 15 | break 16 | } 17 | } 18 | 19 | return d; 20 | } 21 | 22 | fn main() { 23 | 24 | let stdin = stdin(); 25 | let mut lines = stdin.lock().lines().map(Result::unwrap); 26 | 27 | let delta: usize = lines.next().unwrap().parse().unwrap(); 28 | let gene = lines.next().unwrap(); 29 | let _ = lines.next(); 30 | 31 | let mut res: Option<(usize, usize, usize)> = None; 32 | 33 | for (i, elm) in lines.collect::>().iter().enumerate() { 34 | eprintln!("{} : {}", i, elm); 35 | 36 | for (j, _) in elm.as_bytes().iter().enumerate() { 37 | let cur_delta = diff(&gene, &elm[j..], delta); 38 | if delta >= cur_delta { 39 | res = Some( (i, j, cur_delta) ); 40 | break; 41 | } 42 | } 43 | } 44 | 45 | match res { 46 | Some(val) => println!("{} {} {}", val.0, val.1, val.2), 47 | None => println!("NONE"), 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Easy/max-area.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | size_t res{ 0 }; 6 | std::cin.ignore(std::numeric_limits::max(), '\n'); 7 | std::vector< int32_t > bucket{ std::istream_iterator(std::cin), 8 | std::istream_iterator() }; 9 | 10 | for ( auto i{ 0 }; i < std::size(bucket); ++i ) 11 | for ( auto j{ std::size(bucket) - 1 }; j > i; --j ) 12 | res = std::max(res, std::min(bucket[i], bucket[j]) * (j - i)); 13 | 14 | std::cout << res << '\n'; 15 | } -------------------------------------------------------------------------------- /Easy/may-the-triforce-be-with-you.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | main() { 6 | int N; scanf("%d", &N); 7 | char stars[500] = "*"; 8 | 9 | for ( int i = 1; i <= N; i++ ) { // top triangle 10 | printf("%c", (i == 1) ? '.' : ' ' ); 11 | for (int j = 0; j < 2*N-1-i; j++) { printf(" "); } 12 | printf("%s\n", stars); 13 | strcat(stars, "**"); 14 | } 15 | strcpy(stars, "*"); 16 | for (int i = 1; i <= N; i++) { // bottom triangles 17 | for (int j = 1; j <= N-i; j++) { printf(" "); } 18 | printf("%s", stars); 19 | for (int j = 1; j <= N*2-strlen(stars); j++) { printf(" "); } 20 | printf("%s\n", stars); 21 | strcat(stars, "**"); 22 | } 23 | } -------------------------------------------------------------------------------- /Easy/messed-up-mosaics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | std::cin.ignore(std::numeric_limits::max(), '\n'); 6 | std::vector lines{ std::istream_iterator(std::cin), 7 | std::istream_iterator() }; 8 | 9 | auto sz{ std::size(lines.at(0)) }; 10 | for ( auto i{ 0 }; i < std::size(lines); ++i ) { 11 | 12 | auto offset{ lines.at(i).find(lines.at(0)) }; 13 | 14 | for ( auto j{ 0 }; j < std::size(lines.at(i)); ++j ) { 15 | if ( lines.at(i).at(j) != lines.at(0).at((j + sz - offset) % sz) ) { 16 | std::cout << "(" << j << "," << (i - 1) << ")\n"; 17 | return EXIT_SUCCESS; 18 | } 19 | } 20 | } 21 | return EXIT_FAILURE; 22 | } -------------------------------------------------------------------------------- /Easy/metric-units.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Text.RegularExpressions; 3 | 4 | class Solution 5 | { 6 | private static string[] units = { "km", null, null, "m", "dm", "cm", "mm", null, null, "um" }; 7 | 8 | static void Main(string[] args) 9 | { 10 | var expr = Regex.Match(Console.ReadLine(), @"(\d+\.?\d*)(\w+) \+ (\d+\.?\d*)(\w+)"); 11 | 12 | var i1 = Array.IndexOf(units, expr.Groups[2].Value); 13 | var i2 = Array.IndexOf(units, expr.Groups[4].Value); 14 | var v1 = double.Parse(expr.Groups[1].Value); 15 | var v2 = double.Parse(expr.Groups[3].Value); 16 | 17 | var (sum, unit) = i1 < i2 18 | ? (v1 * Math.Pow(10, i2 - i1) + v2, expr.Groups[4].Value) 19 | : (v2 * Math.Pow(10, i1 - i2) + v1, expr.Groups[2].Value); 20 | 21 | Console.WriteLine($"{sum:0.####}{unit}"); 22 | } 23 | } -------------------------------------------------------------------------------- /Easy/mime-type.py: -------------------------------------------------------------------------------- 1 | import sys, math 2 | 3 | N = int(input()) 4 | Q = int(input()) 5 | el=[] 6 | ml=[] 7 | found=0 8 | for i in range(N): 9 | EXT, MT = input().split() 10 | el.append(EXT.lower()) 11 | ml.append(MT) 12 | 13 | for i in range(Q): 14 | fname = input() 15 | ext = fname.split(".") 16 | if("." in fname): 17 | if(ext[-1].lower() in el): print(ml[el.index(ext[-1].lower())]) 18 | else: print("UNKNOWN") 19 | else: 20 | print("UNKNOWN") 21 | -------------------------------------------------------------------------------- /Easy/minimal-palindrome-distance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int doTheJob(char str[], int sz) noexcept { 4 | static int res{ 0 }; 5 | int s{ 0 }, e{ sz - 1 }; 6 | while( s < e ) { 7 | if( str[s] != str[e] && ++res ) 8 | return doTheJob(str + 1, sz - 1); 9 | s++, e--; 10 | } 11 | return res; 12 | } 13 | 14 | int main() 15 | { 16 | std::cin.ignore(std::numeric_limits::max(), '\n'); 17 | std::string s; 18 | getline(std::cin, s); 19 | 20 | std::cout << doTheJob(&s[0], std::size(s) ); 21 | } -------------------------------------------------------------------------------- /Easy/mirrors.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int n{ 0 }; 5 | float t{ 0 }, r{ 0 }; 6 | 7 | std::cin >> n; std::cin.ignore(); 8 | do { 9 | std::cin >> r; std::cin.ignore(); 10 | t = (t + r - 2 * t * r) / (1 - t * r); 11 | } while ( --n && (1 != t)); 12 | 13 | std::cout << std::fixed << std::setprecision(4) << t << std::endl; 14 | } 15 | -------------------------------------------------------------------------------- /Easy/monday-tuesday-happy-days.py: -------------------------------------------------------------------------------- 1 | DoW = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday' ] 2 | MoY = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] 3 | DoM = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] 4 | 5 | # Inputs 6 | leap = int(input()) 7 | initDate = input() 8 | endDate = input() 9 | 10 | # February leap year 11 | DoM[1] += leap 12 | 13 | # Parse inputs to extract dates 14 | stDate = initDate.split() 15 | stDay = DoW.index( stDate[0] ) # Monday -> 0 16 | stMonth = MoY.index( stDate[1] ) # Jan -> 0 17 | stDoM = int ( stDate[2] ) # 2 -> 2 18 | edDate = endDate.split() 19 | edMonth = MoY.index( edDate[0] ) 20 | edDoM = int ( edDate[1] ) 21 | 22 | dlt = 0 23 | PorF = 1 if(edMonth > stMonth) else -1 if (edMonth < stMonth) else 0 # Past or futur 24 | 25 | if PorF > 0: 26 | dlt += DoM[stMonth] - stDoM 27 | stDoM = 0 28 | stMonth += 1 29 | elif PorF < 0: 30 | dlt -= stDoM 31 | stMonth -= 1 32 | stDoM = DoM[stMonth] 33 | 34 | while stMonth != edMonth: 35 | dlt += PorF * DoM[stMonth] 36 | stMonth += PorF 37 | stDoM = 0 if(PorF > 0) else DoM[stMonth] 38 | 39 | dlt += edDoM - stDoM 40 | print(DoW[(stDay + dlt) % 7]) -------------------------------------------------------------------------------- /Easy/morellets-random-lines.js: -------------------------------------------------------------------------------- 1 | const m2nums = _ => readline().split(' ').map(Number); 2 | const [xA, yA, xB, yB] = m2nums(); 3 | const getY = (x, [a, b, c]) => b === 0 ? 1 : -((a * x + c) / b); 4 | const getYs = (a) => [getY(xA, a), getY(xB, a)]; 5 | const redByMin = (a) => a.every(n => n % Math.min(...a) === 0) ? a.map(e => e / Math.min(...a)) : a; 6 | const sameSign = (a) => a[0] < 0 ? a.map(n => -1 * n) : a; 7 | 8 | var eqs = [...new Array(+readline())] 9 | .map(m2nums) 10 | .map(redByMin) 11 | .map(sameSign) 12 | .map(e => e.toString()) 13 | .map(e => e.split(',').map(Number)) 14 | .filter(( t={}, a=> !(t[a]=a in t) )); 15 | 16 | let cntA = 0, cntB = 0; 17 | 18 | eqs.map(getYs).forEach(([_yA, _yB]) => { 19 | if (yA === _yA || yB === _yB) { print('ON A LINE'); quit(); } 20 | if (yA > _yA) { cntA++; } 21 | if (yB > _yB) { cntB++; } 22 | }) 23 | 24 | print( (cntA % 2) === (cntB % 2) ? 'YES' : 'NO'); -------------------------------------------------------------------------------- /Easy/mountain-map-convergence.py: -------------------------------------------------------------------------------- 1 | # Inspired by Niako 2 | 3 | def addCol(T, i, c): 4 | for L in T: L.append(' ') 5 | T[i][-1] = c 6 | 7 | N = int(input()) 8 | M = [1] + list(map(int, input().split())) + [1] 9 | m0 = min(M) 10 | out = [[] for _ in range(max(M)-m0+1)] 11 | 12 | for i in range(1, N + 2): 13 | if M[i-1] < M[i]: 14 | for k in range(M[i-1], M[i]): 15 | addCol(out, k-m0, '/') 16 | else: 17 | for k in range(M[i-1]-1, M[i]-1, -1): 18 | addCol(out, k-m0, '\\') 19 | addCol(out, M[i]-m0, '/') 20 | addCol(out, M[i]-m0, '\\') 21 | 22 | for L in reversed(out): 23 | print(''.join(L[:-2]).rstrip()) 24 | -------------------------------------------------------------------------------- /Easy/mountain-map.py: -------------------------------------------------------------------------------- 1 | input() 2 | IN = list( map( int, input().split() ) ) 3 | h, ret = max( IN ), [] 4 | 5 | for c in IN: 6 | ret.extend(' ' * (h-i-1) + '/' + ' ' * i for i in range( c ) ) 7 | ret.extend(' ' * (h-i-1) + '\\' + ' ' * i for i in range( c-1, -1, -1) ) 8 | for s in zip(*ret): 9 | print( ''.join(s).rstrip() ) -------------------------------------------------------------------------------- /Easy/moves-in-maze.cpp: -------------------------------------------------------------------------------- 1 | // from Remi 2 | 3 | #include 4 | 5 | struct coord { int x, y, n; }; 6 | int main() { 7 | 8 | int w, h, x, y=-1; 9 | std::cin >> w >> h; std::cin.ignore(); 10 | 11 | std::string g[h]; 12 | for (int i=0; i1: ret = [n for n,m,c in P if c==0 if 'alone' not in m] 15 | print(ret[0]+' did it!' if ret else 'It was me!') -------------------------------------------------------------------------------- /Easy/number-derivation.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | res = 0 3 | cpy = n 4 | p = 2 5 | while p <= cpy: 6 | while cpy % p == 0: 7 | cpy //= p 8 | res += n // p 9 | p += 1 10 | print(res) -------------------------------------------------------------------------------- /Easy/number-formatting.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | fn format_number(str: String) -> String { 4 | let decimal_pos = str.find('.').unwrap(); 5 | let before = &str[..decimal_pos].trim_start_matches('0'); 6 | let after = &str[decimal_pos + 1..].trim_end_matches('0'); 7 | 8 | let filled = format!("{}{}{}{}", 9 | "x".repeat(9 - before.len()), 10 | before, 11 | after, 12 | "x".repeat(6 - after.len()) 13 | ); 14 | 15 | let mut result = String::new(); 16 | 17 | for (i, marker) in (0..filled.len()).step_by(3).zip( [",", ",", ".", ".", ""]) { 18 | result.push_str(&filled[i..i+3]); 19 | result.push_str(marker); 20 | } 21 | 22 | result 23 | } 24 | 25 | fn main() { 26 | let mut input_line = String::new(); 27 | io::stdin().read_line(&mut input_line).unwrap(); 28 | 29 | let mut n = input_line.trim_matches('\n').replace('x', "0").to_string(); 30 | n.retain(|c: char| c.is_digit(10)); 31 | n.insert(9, '.'); 32 | 33 | println!("{}", format_number( format!("{:.6}", n.parse::().unwrap()/ 2f64) )); 34 | } 35 | -------------------------------------------------------------------------------- /Easy/number-of-digits.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | macro_rules! parse_input { 4 | ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap()) 5 | } 6 | 7 | 8 | fn main() { 9 | let mut input_line = String::new(); 10 | io::stdin().read_line(&mut input_line).unwrap(); 11 | let n = parse_input!(input_line, i64); 12 | 13 | let mut input_line = String::new(); 14 | io::stdin().read_line(&mut input_line).unwrap(); 15 | let k = parse_input!(input_line, i64); 16 | 17 | let mut res = 0i64; 18 | let mut f = 1i64; 19 | 20 | while n >= f { 21 | let high = n / (f * 10); 22 | let cur = (n / f) % 10; 23 | let low = n % f; 24 | 25 | // (high * f) : digit combinations above current position 26 | // (cur == k) * (low + 1) : extra occurrences if the current digit exactly matches k 27 | // (cur > k) * f : extra occurrences if the current digit is larger than k 28 | res += high * f + (cur == k) as i64 * (low + 1) + (cur > k) as i64 * f; 29 | f *= 10; 30 | } 31 | println!("{}", res); 32 | } 33 | -------------------------------------------------------------------------------- /Easy/number-partition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void P(int N, int k, std::deque cP) noexcept { 4 | if ( 0 == N ) { 5 | std::stringstream ss; 6 | std::string res; 7 | for ( const auto& elm : cP ) { ss << elm << ' '; } 8 | res = ss.str(); 9 | res.pop_back(); 10 | std::cout << res << std::endl; 11 | } 12 | else { 13 | for ( int i{ k }; i > 0; i-- ) { 14 | auto cPP{ cP }; 15 | cPP.push_back( i ); 16 | P(N - i, std::min(N - i, i), cPP ); 17 | } 18 | } 19 | } 20 | 21 | int main() { 22 | int n; 23 | std::cin >> n; std::cin.ignore(); 24 | 25 | P(n, n, {}); 26 | } -------------------------------------------------------------------------------- /Easy/odd-quad-out.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int sz, oddQuad, oddValue, standardValue, qRow, qCol; 5 | std::map sums, cmpts; 6 | 7 | std::cin >> sz; std::cin.ignore(); 8 | 9 | for (int i{ 0 }; i < sz; i++) { 10 | std::string row; 11 | getline(std::cin, row); 12 | qRow = (i < sz / 2 ) ? 0 : 1; 13 | for ( int j{ 0 }; j < std::size(row); ++j ) { 14 | qCol = (j < sz / 2 ) ? 0 : 1; 15 | if ( '.' != row[j] ) { sums[qRow * 2 + qCol + 1] += row[j] - '0'; } 16 | } 17 | } 18 | 19 | for (const auto& [k,v] : sums) { cmpts[v]++; } 20 | for (const auto& [k,v] : sums) { 21 | if ( 1 == cmpts[v] ) { oddValue = v, oddQuad = k; } 22 | else { standardValue = v; } 23 | } 24 | 25 | std::cout << "Quad-" << oddQuad << " is Odd-Quad-Out" << std::endl; 26 | std::cout << "It has value of " << oddValue << std::endl; 27 | std::cout << "Others have value of " << standardValue << std::endl; 28 | } -------------------------------------------------------------------------------- /Easy/offset-arrays.py: -------------------------------------------------------------------------------- 1 | arrs = {} 2 | for _ in range(int(input())): 3 | a,_,*v = input().split() 4 | l = a.find('[') 5 | s,e = map(int,a[l+1:-1].split('..')) 6 | arrs[a[:l]] = dict(zip(range(s,e+1),map(int,v))) 7 | *x,s = input().replace(']','').split('[') 8 | s = int(s) 9 | for a in x[::-1]: s = arrs[a][s] 10 | print(s) 11 | -------------------------------------------------------------------------------- /Easy/onboarding.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | while (1) 7 | { 8 | std::string e1, e2; 9 | int d1, d2; 10 | 11 | std::cin >> e1 >> d1 >> e2 >> d2; std::cin.ignore(); 12 | std::cout << ( (d1 < d2) ? e1 : e2 ) << std::endl; 13 | } 14 | } -------------------------------------------------------------------------------- /Easy/order-of-succession.py: -------------------------------------------------------------------------------- 1 | class Sol: 2 | def __init__(self, name, parent, birth, death, religion, gender): 3 | self.name = name 4 | self.parent = parent 5 | self.birth = int(birth) 6 | self.death = int(death) if death != '-' else None 7 | self.religion = religion 8 | self.isfemale = gender == 'F' 9 | self.children = [] 10 | 11 | def addChild(self, child): 12 | if child.parent == self.name: self.children += [child] 13 | else: 14 | for i in self.children: i.addChild(child) 15 | 16 | def traverse(self): 17 | succession = [] 18 | if not self.death and self.religion == 'Anglican': succession += [self] 19 | sortedChildren = sorted(self.children, key=lambda child: (child.isfemale, child.birth)) 20 | for child in sortedChildren: succession += child.traverse() 21 | return succession 22 | 23 | n = int(input()) 24 | succ = Sol(*input().split()) 25 | 26 | for i in range(n - 1): 27 | i = Sol(*input().split()) 28 | succ.addChild(i) 29 | 30 | for i in succ.traverse(): 31 | print(i.name) -------------------------------------------------------------------------------- /Easy/organic-compounds.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | class Solution { 5 | public static void main(String args[]) { 6 | Scanner in = new Scanner(System.in); 7 | int N = in.nextInt(); 8 | String c[] = new String[N]; in.nextLine(); 9 | 10 | for (int i = 0; i < N; i++) { c[i] = in.nextLine().toUpperCase(); } 11 | for (int i = 0; i < N; i++) { 12 | if (c[i].indexOf('C')==-1) { continue; } 13 | for (int j = 0; j < c[i].length()-2; j++) { 14 | if (c[i].substring(j,j+2).equals("CH")) { 15 | int b = Integer.parseInt(""+c[i].charAt(j+2)); 16 | try { b += Integer.parseInt(""+c[i-1].charAt(j+1)); } catch (Exception e) {} 17 | try { b += Integer.parseInt(""+c[i+1].charAt(j+1)); } catch (Exception e) {} 18 | try { b += Integer.parseInt(""+c[i].charAt(j-2) ); } catch (Exception e) {} 19 | try { b += Integer.parseInt(""+c[i].charAt(j+4) ); } catch (Exception e) {} 20 | 21 | if (b!=4) { System.out.println("INVALID"); return; } 22 | j+=5; 23 | } 24 | } 25 | } 26 | System.out.print("VALID"); 27 | } 28 | } -------------------------------------------------------------------------------- /Easy/pirates-treasure.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int W, H; 4 | void check(int i, int j, int map[H][W]) { 5 | int indexes[5] = {i-1, i+1, j-1, j+1, 0}; 6 | if ( map[i][j] != 0 ) return; 7 | if ( i == H -1 ) { indexes[1] = i; ++indexes[4]; } 8 | else if ( i == 0 ) { indexes[0] = i; ++indexes[4]; } 9 | if ( j == W -1 ) { indexes[3] = j; ++indexes[4]; } 10 | else if ( j == 0 ) { indexes[2] = j; ++indexes[4]; } 11 | 12 | int l_cmpt = 0; 13 | for (int c = indexes[0]; c <= indexes[1]; ++c) for (int d = indexes[2]; d <= indexes[3]; ++d) l_cmpt += map[c][d]; 14 | if ( (l_cmpt == 8) || ( (l_cmpt == 5) && (indexes[4] == 1) ) || ( (l_cmpt == 3) && (indexes[4] == 2) ) ) printf("%d %d", j, i); 15 | } 16 | 17 | void main() { 18 | scanf("%d%d", &W, &H); 19 | int map[H][W]; 20 | for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) scanf("%d", &map[i][j]); 21 | for (int i = 0; i < H; i++) for (int j = 0; j < W; j++) check(i, j, map); 22 | } -------------------------------------------------------------------------------- /Easy/power-of-thor-1.js: -------------------------------------------------------------------------------- 1 | var inputs = readline().split(' '); 2 | var lightX = parseInt(inputs[0]); 3 | var lightY = parseInt(inputs[1]); 4 | var initialTX = parseInt(inputs[2]); 5 | var initialTY = parseInt(inputs[3]); 6 | 7 | while (true) 8 | { 9 | const remainingTurns = parseInt(readline()); 10 | var direction = ""; 11 | 12 | if (initialTY < lightY) { initialTY++; direction = "S"; } 13 | else if (initialTY > lightY) { initialTY--; direction = "N"; } 14 | 15 | if (initialTX < lightX) { initialTX++; direction += "E"; } 16 | else if (initialTX > lightX) { initialTX--; direction += "W"; } 17 | 18 | console.log(direction); 19 | } -------------------------------------------------------------------------------- /Easy/prefix-code.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | int N, val, maxS(0); 10 | string key, test; 11 | map dic; 12 | 13 | cin >> N; cin.ignore(); 14 | while ( N-- && cin >> key >> val ) 15 | { 16 | dic[key] = val; cin.ignore(); 17 | if ( maxS < key.size() ) { maxS = key.size(); } 18 | } 19 | cin >> test; cin.ignore(); 20 | 21 | bool isOk (true); 22 | int st_idx(0 ), cur_idx (-1 ); 23 | string cur, res; 24 | while( isOk && ++cur_idx < test.length() ) 25 | { 26 | cur += test.at(cur_idx); 27 | if ( cur.size() > maxS ) 28 | { 29 | isOk = false; 30 | } 31 | else if ( dic.find( cur ) != dic.end() ) 32 | { 33 | res += (char)dic[cur]; 34 | cur.clear(); 35 | st_idx = cur_idx + 1; 36 | } 37 | } 38 | 39 | isOk = cur.empty(); 40 | 41 | cout << ( isOk ? res : ("DECODE FAIL AT INDEX " + to_string(st_idx)) ) << endl; 42 | } -------------------------------------------------------------------------------- /Easy/probability-for-dummies.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define OUTS 38 4 | 5 | int main() { 6 | std::mt19937 rand_gen(time(nullptr)); 7 | int m, n, totals(1e4), successes(0); 8 | 9 | std::cin >> m >> n; 10 | for ( int i = 0; i < totals; ++i ) { 11 | std::set results; 12 | for ( int j = 0; j < n; ++j ) 13 | results.insert( rand_gen() % OUTS ); 14 | if ( std::size(results) >= m ) ++successes; 15 | } 16 | 17 | std::cout << round( static_cast(successes) / totals * 100 ) << "%"; 18 | } -------------------------------------------------------------------------------- /Easy/random-walk.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef std::pair Pos; 4 | 5 | template 6 | std::pair& operator+=(std::pair & l,const std::pair & r) { 7 | l.first += r.first; 8 | l.second += r.second; 9 | 10 | return l; 11 | } 12 | 13 | int main() 14 | { 15 | int a, b, m, res{ 0 }, D{0}; 16 | const std::array moves{ { {0, 1}, {0, -1}, {-1, 0}, {1, 0} } }; 17 | const Pos origin{0,0}; 18 | Pos curPos{origin}; 19 | 20 | std::cin >> a >> b >> m; std::cin.ignore(); 21 | 22 | do { 23 | D = ( a * D + b ) % m; 24 | curPos += moves[D%4]; 25 | ++res; 26 | } while ( origin != curPos ); 27 | 28 | std::cout << res << std::endl; 29 | } -------------------------------------------------------------------------------- /Easy/rectangle-partition.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | main() 9 | { 10 | int w, h, x_mes, y_mes, res(0), tmp; 11 | cin >> w >> h >> x_mes >> y_mes; cin.ignore(); 12 | set l_x = { 0, w }, l_y = { 0, h }; 13 | map map_x, map_y; 14 | 15 | map_x[w] = 1; map_y[h] = 1; 16 | for (int i = 0; i < x_mes && cin >> tmp; i++) { 17 | for ( auto& it : l_x ) { map_x[abs(it - tmp)] ++; } 18 | l_x.insert(tmp); cin.ignore(); 19 | } 20 | for (int i = 0; i < y_mes && cin >> tmp; i++) { 21 | for ( auto& it : l_y ) { map_y[abs(it - tmp)] ++; } 22 | l_y.insert(tmp); cin.ignore(); 23 | } 24 | 25 | for ( auto &it : map_x ) 26 | if ( map_y.find(it.first) != map_y.end() ) { res += it.second * map_y[it.first]; } 27 | cout << res << endl; 28 | } -------------------------------------------------------------------------------- /Easy/rectangular-block-spinner.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import numpy as np 3 | 4 | S = int(input()) 5 | A = int(input()) 6 | 7 | d = np.loadtxt(sys.stdin, comments=None, dtype=str) 8 | d = np.rot90(d, k=(A-45)/90%4) 9 | 10 | for i in range(S-1,-S,-1): 11 | sp = " "*abs(i) 12 | print(sp + " ".join(d.diagonal(i)) + sp) -------------------------------------------------------------------------------- /Easy/reverse-fizzbuzz.rb: -------------------------------------------------------------------------------- 1 | f = [] 2 | b = [] 3 | n = gets.to_i 4 | st = nil 5 | (1..n).each do |i| 6 | line = gets.chomp 7 | f << i if line.include?('Fizz') 8 | b << i if line.include?('Buzz') 9 | if st.nil? and line.to_i != 0 10 | cur = line.to_i 11 | st = cur - i 12 | end 13 | end 14 | fizz = f.size==1 ? f[0]+st : f[1]-f[0] 15 | buzz = b.size==1 ? b[0]+st : b[1]-b[0] 16 | 17 | puts [fizz,buzz]*' ' -------------------------------------------------------------------------------- /Easy/robot-reach.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template 4 | using V = std::vector; 5 | 6 | int sumDigits(int n) noexcept { 7 | int res{ 0 }; 8 | while( n > 0 ) { res += n % 10; n /= 10; } 9 | return res; 10 | } 11 | 12 | int main() 13 | { 14 | int r, c, t; 15 | std::cin >> r >> c >> t; std::cin.ignore(); 16 | 17 | V< V > mem{ static_cast(r), V(c, 0) }; 18 | for ( auto i{ 0 }; i < r; ++i ) 19 | for ( auto j{ 0 }; j < c; ++j ) 20 | mem[i][j] = sumDigits(i) + sumDigits(j); 21 | 22 | std::function doTheJob{ [&](int row, int col){ 23 | if ( row >= r || col >= c || mem[row][col] > t ) 24 | return 0; 25 | 26 | mem[row][col] = t + 1; 27 | 28 | return doTheJob(row, col + 1) + doTheJob(row + 1, col) + 1; 29 | } }; 30 | 31 | std::cout << doTheJob(0, 0) << '\n'; 32 | } -------------------------------------------------------------------------------- /Easy/robot-show.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() { 9 | int L, N, l_cur; 10 | cin >> L >> N; cin.ignore(); 11 | vector v(N); 12 | 13 | for ( int i = 0; i < N; i++ ) { cin >> v[i]; } 14 | 15 | const auto [ l_min, l_max ] = minmax_element( v.begin(), v.end() ); 16 | cout << std::max(L - *l_min, *l_max) << endl; 17 | } -------------------------------------------------------------------------------- /Easy/rotating-arrows.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int w, h, x, y, ret{0}; 6 | std::cin >> w >> h >> x >> y; std::cin.ignore(); 7 | 8 | std::vector< std::string > grid(h); 9 | for ( auto& line : grid ) { std::cin >> line; std::cin.ignore(); } 10 | 11 | auto it = [&](int& x, int& y) { 12 | auto& val = grid[y][x]; 13 | switch(val) { 14 | case '<': val = '^'; --y; break; 15 | case '>': val = 'v'; ++y; break; 16 | case 'v': val = '<'; --x; break; 17 | case '^': val = '>'; ++x; break; 18 | default: return false; 19 | } 20 | 21 | return x >= 0 && x < w && y >= 0 && y < h; 22 | }; 23 | 24 | int xi{x}, yi{y}; 25 | while( ++ret ) 26 | if ( !it(xi, yi) || ( xi == x && yi == y)) break; 27 | 28 | std::cout << ret << '\n'; 29 | } -------------------------------------------------------------------------------- /Easy/rugby-score.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main() { 4 | int N; scanf("%d", &N); 5 | for ( int tri = 0; tri*5 <= N; tri++ ) 6 | for ( int transf = 0; (transf <= tri) && (transf*2 <= N - tri * 5); ++transf ) 7 | if ( ( (N - tri * 5 - transf * 2) % 3) == 0 ) 8 | printf("%d %d %d\n", tri, transf, (N - tri * 5 - transf * 2) / 3); 9 | } -------------------------------------------------------------------------------- /Easy/shadow-casting.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int N; std::cin >> N; std::cin.ignore(); 6 | std::vector grid( N + 2, std::string(128, ' ') ); 7 | 8 | const auto rtrim = [](std::string &s) { 9 | s.erase(std::find_if(std::rbegin(s), std::rend(s), 10 | std::not1(std::ptr_fun(std::isspace))).base(), std::end(s)); 11 | }; 12 | 13 | for (int i = 0; i < N; i++) { 14 | std::string tmp; 15 | getline( std::cin, tmp ); 16 | for ( int j = 0; j < std::size(tmp); ++j ) 17 | if ( !isspace(tmp[j]) ) { grid[i][j]=tmp[j]; grid[i+1][j+1] = '-'; grid[i+2][j+2] = '`'; } 18 | } 19 | 20 | for ( auto& s : grid ) { rtrim(s); std::cout << s << "\n"; } 21 | } -------------------------------------------------------------------------------- /Easy/shoot-enemy-aircraft.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Aircraft { 4 | int _row{ 0 }, _col{ 0 }; 5 | constexpr int operator-(const Aircraft& rhs) noexcept { 6 | return abs(_col - rhs._col) - abs(_row - rhs._row); 7 | } 8 | }; 9 | 10 | int main() 11 | { 12 | int n; 13 | std::cin >> n; std::cin.ignore(); 14 | 15 | std::vector< Aircraft > aircrafts; 16 | Aircraft launcher; 17 | std::set< int > fireTurns; 18 | std::string curLine; 19 | for ( auto row{ 0 }; row < n; ++row ) { 20 | getline(std::cin, curLine); 21 | for ( auto col{ 0 }; col < std::size(curLine); ++col ) { 22 | switch( curLine[col] ) { 23 | case '>' : 24 | case '<' : aircrafts.push_back({row, col}); break; 25 | case '^' : launcher = {row, col}; break; 26 | default : break; 27 | } 28 | } 29 | } 30 | 31 | for ( const auto& aircraft : aircrafts ) 32 | fireTurns.insert( launcher - aircraft ); 33 | 34 | for ( auto curTurn{ 0 }; const auto& nxtFire : fireTurns ) { 35 | for ( auto i{ 0 }; i < (nxtFire - curTurn - 1); ++i ) 36 | std::cout << "WAIT\n"; 37 | std::cout << "SHOOT\n"; 38 | curTurn = nxtFire; 39 | } 40 | } -------------------------------------------------------------------------------- /Easy/should-bakers-be-frugal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | float n, d; 6 | int res_wasteful{ 0 }, res_frugal{ 0 }; 7 | std::cin >> n >> d; std::cin.ignore(); 8 | 9 | double biscuit_area = M_PI * (d*0.5) * (d*0.5); 10 | 11 | res_wasteful = floor(n/d) * floor(n/d); 12 | res_frugal = floor( (n*n - d*d + biscuit_area) / biscuit_area ); 13 | 14 | std::cout << res_frugal - res_wasteful << '\n'; 15 | } -------------------------------------------------------------------------------- /Easy/simple-auto-scaling.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int S, M, nb; 6 | std::cin >> S >> M; 7 | 8 | std::stringstream ss; 9 | std::vector srvs(S, 0), cap{srvs}; 10 | 11 | for (auto& capacity : cap) std::cin >> capacity; 12 | 13 | for (auto i = 0; i < M; ++i) { 14 | ss.str(std::string()); 15 | for (auto j = 0; j < S; ++j) { 16 | std::cin >> nb; 17 | nb = ceil(nb / static_cast(cap[j])); // Services can handle at least 1 client 18 | ss << nb - srvs[j] << " "; 19 | srvs[j] = nb; 20 | } 21 | auto res{ ss.str() }; 22 | res.pop_back(); 23 | std::cout << res << "\n"; 24 | } 25 | } -------------------------------------------------------------------------------- /Easy/simple-awale.js: -------------------------------------------------------------------------------- 1 | ra = _ => readline().split(' ').map(Number); 2 | i = +readline(mB = ra(opB = ra())); 3 | 4 | const b = mB, op = opB, size = b.length; 5 | N = b[i]; 6 | 7 | for (b[i++] = 0; N-- > 0; i = i % (2*size-1)) { (i < size) ? b[i++]++ : op[i++ - size]++ } 8 | 9 | rpl = arr => arr.join(' ').replace(/(\d)$/, '[$1]'); 10 | print(rpl(op)); 11 | print(rpl(b)); 12 | if (i == b.length) print('REPLAY'); -------------------------------------------------------------------------------- /Easy/simple-load-balancing.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int N, K, S, i{ 0 }; 6 | std::cin >> N >> K; std::cin.ignore(); 7 | 8 | std::vector Li{ std::istream_iterator(std::cin), 9 | std::istream_iterator() }; 10 | 11 | std::sort(std::begin(Li), std::end(Li)); 12 | 13 | while ( ++i S ) { Li[0] = Li[i]; K -= S; } 17 | else { Li[0] += K/i; K = 0; } 18 | } 19 | 20 | std::cout << ( K ? ( K % N ? 1 : 0 ) : Li[N-1] - Li[0] ); 21 | } -------------------------------------------------------------------------------- /Easy/smooth.sh: -------------------------------------------------------------------------------- 1 | xargs factor | sed '1d; s/.*://; s/ [235]//g; s/..*/DEFEAT/; s/^$/VICTORY/' -------------------------------------------------------------------------------- /Easy/snake-sort-2d.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef std::istream IS; 4 | typedef std::ostream OS; 5 | 6 | struct Apple { 7 | friend IS& operator>>(IS& is, Apple& in ) { return is >> in._name >> in._row >> in._col; } 8 | friend OS& operator<<(OS& os, const Apple& out) { return os << out._name; } 9 | 10 | std::string _name; 11 | int _row, _col; 12 | }; 13 | 14 | int main() 15 | { 16 | int N; 17 | Apple cur_apple; 18 | std::map > apples; 19 | 20 | std::cin >> N; 21 | for ( auto i{0}; i < N; ++i ) { 22 | std::cin >> cur_apple; 23 | apples[cur_apple._row].push_back(cur_apple); 24 | } 25 | 26 | auto right{ true }; 27 | std::stringstream ss; 28 | for ( auto& [row, apple_row] : apples ) { 29 | std::sort(std::begin(apple_row), 30 | std::end (apple_row), 31 | [&right](const auto& a, const auto& b){ 32 | return right ? a._col < b._col : b._col < a._col; 33 | }); 34 | right = !right; 35 | for ( const auto& apple : apple_row ) 36 | ss << apple << ','; 37 | } 38 | auto ret{ ss.str() }; 39 | if ( !std::empty(ret) ) ret.pop_back(); 40 | std::cout << ret; 41 | } -------------------------------------------------------------------------------- /Easy/someones-acting-sus----.py: -------------------------------------------------------------------------------- 1 | L = int(input()) 2 | o = input() 3 | N,_ = map(int, input().split()) 4 | for _ in range(N): 5 | p = input().strip('#') 6 | sus = False 7 | j = 0 8 | i = d = 1 9 | while i30: 23 | mini.append(v) 24 | break 25 | mini.sort() 26 | print(mini[0]) 27 | place=0 28 | for e in vitesse: 29 | nb=chute=0 30 | for r in virage: 31 | nb+=1 32 | if 90-math.degrees(math.atan((e**2)/(r*9.81)))<=30: 33 | rank.append((nb,e,player[place])) 34 | chute=1 35 | break 36 | if chute==1: 37 | chute=0 38 | else: 39 | rank.append((999,e,player[place])) 40 | place+=1 41 | rank.sort(reverse=True) 42 | print("y") 43 | for e in rank: 44 | x,y,z=e 45 | print(z) -------------------------------------------------------------------------------- /Easy/substitution-encoding.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | int main() 5 | { 6 | std::map< char, std::string > dic{}; 7 | std::string row, mesg; 8 | int rows; 9 | 10 | std::cin >> rows; std::cin.ignore(); 11 | 12 | for ( int i = 0; i < rows; ++i ) { 13 | int j{ 0 }; 14 | getline(std::cin, row); 15 | std::for_each( std::begin(row), std::end(row), [&dic, &i, &j](const auto& c){ 16 | if ( !isspace(c) ) 17 | dic[c] = std::to_string(i) + std::to_string(j++); 18 | }); 19 | } 20 | 21 | getline(std::cin, mesg); 22 | for ( const auto& c : mesg ) 23 | std::cout << dic[c]; 24 | std::cout << "\n"; 25 | } 26 | -------------------------------------------------------------------------------- /Easy/sudoku-validator.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | class Grid: 4 | def __init__(self, d): self.d = d 5 | def _row(self, i ): return len(set(self.d[i])) == 9 6 | def _col(self, j ): return len(set([self.d[i][j] for i in range(9)])) == 9 7 | def _sub(self, i, j ): return len(set([self.d[k][l] for k in range(i, i+3) for l in range(j, j+3)])) == 9 8 | def _slv(self ): 9 | for i in range(9): 10 | if not self._row(i) or not self._col(i): return False 11 | for i in (0, 3, 6): 12 | for j in (0, 3, 6): 13 | if not self._sub(i, j): return False 14 | return True 15 | print(str(Grid([list(map(int, input().split())) for i in range(9)])._slv()).lower()) -------------------------------------------------------------------------------- /Easy/sum-of-spirals-diagonals.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | long long N; 5 | std::cin >> N; 6 | std::cout << (8*N*N*N - 3*N*N + 4*N - (6*N*N-3) * (N%2))/6; 7 | } -------------------------------------------------------------------------------- /Easy/teds-compiler.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | std::string line; 6 | int ret{ 0 }; 7 | std::stack stk{ }; 8 | 9 | getline(std::cin, line); 10 | 11 | for ( int i = 0; i < std::size(line); ++i ) { 12 | if ( '<' == line[i] ) stk.push('<'); 13 | else { 14 | if ( stk.empty() ) break; 15 | stk.pop(); 16 | if ( stk.empty() ) ret = i + 1; 17 | } 18 | } 19 | 20 | std::cout << ret << '\n'; 21 | } -------------------------------------------------------------------------------- /Easy/temperatures.js: -------------------------------------------------------------------------------- 1 | const n = parseInt(readline()) ; 2 | var inputs = readline().split(' '); 3 | var res = n > 0 ? 5526 : 0; 4 | 5 | for (let i = 0; i < n; i++) 6 | { 7 | const t = parseInt(inputs[i]); 8 | res = ( Math.abs(t) == Math.abs(res) && t > 0 ) ? t : (Math.abs(t) < Math.abs(res)) ? t : res; 9 | } 10 | 11 | console.log(res); -------------------------------------------------------------------------------- /Easy/text-formatting.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def setMajs(s): 4 | if not s: return '' 5 | txt_c = list(s) 6 | txt_c[0] = txt_c[0].upper() 7 | return ''.join(txt_c) 8 | 9 | txt = input().lower().strip() 10 | txt = re.sub(r'\s{2,}' , ' ' , txt) 11 | txt = re.sub(r'\s?[^\s\w\d]\s?', lambda c: c.group().strip() , txt) 12 | txt = re.sub(r'[^\s\w\d]+' , lambda c: c.group().strip()[0], txt) 13 | txt = '.'.join(setMajs(s) for s in txt.split('.')) 14 | txt = re.sub(r'[^\s\w\d]' , lambda c: c.group() + ' ' , txt) 15 | 16 | print(txt.strip()) 17 | -------------------------------------------------------------------------------- /Easy/the-broken-editor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int curs{ 0 }; 6 | std::string in, out; 7 | getline(std::cin, in); 8 | 9 | std::for_each(std::begin(in), 10 | std::end(in), 11 | [&out, &curs](const auto& c) { 12 | switch(c) { 13 | case '<': if ( curs > 0 ) --curs; break; 14 | case '>': if ( curs < std::size(out) ) ++curs; break; 15 | case '-': if ( curs > 0 ) { out.erase(--curs, 1); } break; 16 | default : out.insert(curs++, 1, c); break; 17 | } 18 | }); 19 | 20 | std::cout << out << '\n'; 21 | } -------------------------------------------------------------------------------- /Easy/the-descent.js: -------------------------------------------------------------------------------- 1 | while (true) 2 | { 3 | var maxH = -1; 4 | var resH = -1; 5 | 6 | for (let i = 0; i < 8; i++) 7 | { 8 | const mountainH = parseInt(readline()); 9 | 10 | if ( mountainH >= maxH ) { maxH = mountainH; resH = i; } 11 | } 12 | 13 | console.log(resH); 14 | } -------------------------------------------------------------------------------- /Easy/the-michelangelo-code.py: -------------------------------------------------------------------------------- 1 | w = ''.join(i.lower() for i in input() if i.isalpha()) 2 | for i in sorted([input() for i in range(int(input()))], key=lambda x: len(x), reverse=True): 3 | cpy = w 4 | for j in range(w.count(i[0])): 5 | s = cpy.index(i[0]) 6 | for n in range(2, len(cpy)): 7 | if cpy[s:s + len(i) * n:n] == i: 8 | x = cpy[s:s + len(i) * n - n + 1] 9 | print(''.join(x[k].upper() if x[k] in i and k % n == 0 else x[k] for k in range(len(x)))) 10 | exit() 11 | cpy = cpy[s+1:] -------------------------------------------------------------------------------- /Easy/the-mystic-rectangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int x, y, u, v; 6 | std::cin >> x >> y >> u >> v; 7 | 8 | auto dx{std::min((200+(x-u)%200)%200,(200+(u-x)%200)%200)}, 9 | dy{std::min((150+(y-v)%150)%150,(150+(v-y)%150)%150)}; 10 | 11 | std::cout << std::fixed << std::setprecision(1) << (dx*.3 + dy*.4 - std::min(dx,dy)*.2) << "\n"; 12 | } -------------------------------------------------------------------------------- /Easy/the-prime-twins---part-one.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | macro_rules! parse_input { 4 | ($x:expr, $t:ident) => ($x.trim().parse::<$t>().unwrap()) 5 | } 6 | 7 | fn is_prime(num: u64) -> bool { 8 | if num < 2 { 9 | return false; 10 | } 11 | for i in 2..=((num as f64).sqrt() as u64) { 12 | if num % i == 0 { 13 | return false; 14 | } 15 | } 16 | true 17 | } 18 | 19 | fn find_prime_twins(start: u64) -> (u64, u64) { 20 | let mut num = start + 1; 21 | loop { 22 | if is_prime(num) && is_prime(num + 2) { 23 | return (num, num + 2); 24 | } 25 | num += 1; 26 | } 27 | } 28 | 29 | fn main() { 30 | let mut input_line = String::new(); 31 | io::stdin().read_line(&mut input_line).unwrap(); 32 | 33 | let (a, b) = find_prime_twins(parse_input!(input_line, u64)); 34 | 35 | println!("{} {}", a, b); 36 | } 37 | -------------------------------------------------------------------------------- /Easy/the-river-i.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void next(long long* x) { 6 | long long l_tmp = *x; 7 | while (l_tmp) { *x += l_tmp %10; l_tmp /= 10; } 8 | } 9 | 10 | void main() { 11 | long long r1, r2; 12 | scanf("%lld", &r1); scanf("%lld", &r2); 13 | while ( r1 != r2 ) ( r1 < r2 ) ? next(&r1) : next(&r2); 14 | printf("%d\n", r1); 15 | } -------------------------------------------------------------------------------- /Easy/the-river-ii.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long r1; 4 | char tested[100000] = {0}; 5 | 6 | void next(long* x) { 7 | long l_tmp = *x; 8 | while (l_tmp) { *x += l_tmp %10; l_tmp /= 10; } 9 | tested[*x] = 1; 10 | } 11 | 12 | int testFlow(long i) { 13 | while ( i < r1 && (tested[i] == 0) ) { next(&i); if ( i == r1) return 1; } 14 | return 0; 15 | } 16 | 17 | void main() { 18 | scanf("%lld", &r1); 19 | for ( long i = r1 - 1; i > 0; --i ) if ( testFlow(i) ){ printf("YES\n"); return; } 20 | printf("NO\n"); 21 | } -------------------------------------------------------------------------------- /Easy/the-travelling-salesman-problem.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct _Pt { int x, y; } Pt; 6 | 7 | float d( Pt* p1, Pt* p2) { 8 | float tx = p1->x - p2->x, ty = p1->y - p2->y; 9 | return sqrt(tx*tx + ty*ty); 10 | } 11 | 12 | main() { 13 | int N; scanf("%d", &N); 14 | float res = 0.f; 15 | Pt c[N], init; 16 | for (int i = 0; i < N; i++) { scanf("%d%d", &c[i].x, &c[i].y); } 17 | init = c[0]; 18 | 19 | while(N > 1) { 20 | float minD = 1e9; int minIdx = 0; 21 | for (int i = 1; i < N; i++) { 22 | float tmp_d = d(c, c+i); 23 | if ( tmp_d< minD ) { minD = tmp_d; minIdx = i; } 24 | } 25 | res += minD; 26 | c[0] = c[minIdx]; 27 | memmove( c+minIdx, c+minIdx+1, (N-1-minIdx)*sizeof(Pt) ); 28 | N--; 29 | } 30 | printf("%d\n", (int)round(res + d(&init, &c[0])) ); 31 | } -------------------------------------------------------------------------------- /Easy/tree-paths.rb: -------------------------------------------------------------------------------- 1 | N = gets.to_i 2 | V = gets.to_i 3 | M = gets.to_i 4 | T = {} 5 | p = [0]*(N+1) 6 | 7 | M.times do 8 | x, l, r = gets.split.map(&:to_i) 9 | T[x] = [l,r] 10 | p[l] += 1 11 | p[r] += 1 12 | end 13 | 14 | root = p.rindex(0) 15 | q = Queue.new 16 | q << [root, []] 17 | res = nil 18 | while !q.empty? 19 | x,path = q.pop 20 | if x == V 21 | res = path 22 | end 23 | 24 | c = T[x] 25 | next if c.nil? 26 | 27 | q << [c[0], path + ['Left' ]] 28 | q << [c[1], path + ['Right']] 29 | end 30 | puts res.empty? ? 'Root' : res.join(' ') -------------------------------------------------------------------------------- /Easy/tricky-number-verifier.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | def print_validity(str): 4 | if len(str) != 10 or str[0] == '0' or not str.isdigit(): 5 | return print('INVALID SYNTAX') 6 | lll, x, ddmmyy = str[:3], str[3], str[4:] 7 | 8 | try: 9 | datetime.strptime(ddmmyy, "%d%m%y") 10 | except ValueError: 11 | return print('INVALID DATE') 12 | 13 | tmp = sum(int(d) * int(m) for d, m in zip(str, '3790584216')) % 11 14 | 15 | if tmp == 10: 16 | print_validity(f'{int(lll) + 1}0{ddmmyy}') 17 | elif int(x) != tmp: 18 | print(f'{lll}{tmp}{ddmmyy}') 19 | else: 20 | print('OK') 21 | 22 | for _ in range(int(input())): 23 | print_validity(input()) -------------------------------------------------------------------------------- /Easy/ulam-spiral.py: -------------------------------------------------------------------------------- 1 | #From CompOzr 2 | 3 | n = int(input()) 4 | 5 | grid = [[0 for i in range(n)]for j in range(n)] 6 | 7 | D = [[0, 1], [-1, 0], [0, -1], [1, 0]] 8 | 9 | mid = n//2 10 | y = mid 11 | x = mid 12 | d = 0 13 | l = 0 14 | i = 1 15 | 16 | while i <= n*n: 17 | if d == 0: l += 1 18 | 19 | while x not in [-1, n] and y not in [-1, n]: 20 | grid[y][x] = i 21 | 22 | next_y = y + D[d][0] 23 | next_x = x + D[d][1] 24 | 25 | if abs(next_y - mid) > l or abs(next_x - mid) > l: break 26 | 27 | y = next_y 28 | x = next_x 29 | i += 1 30 | 31 | d = (d + 1) % 4 32 | 33 | for row in grid: print(*[' #'[x > 1 and all(x % i for i in range(2, x))] for x in row]) -------------------------------------------------------------------------------- /Easy/unit-fractions.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() 4 | { 5 | long n, N; 6 | scanf("%ld", &n); 7 | N = n*n; 8 | for( long i = 1; i < N/2+1; i++ ) 9 | { 10 | long x = n+N/i, y = n+i; 11 | if ( x < y ) { break; } 12 | if ( N % i == 0 ) { printf("1/%ld = 1/%ld + 1/%d\n", n, x, y); } 13 | } 14 | } -------------------------------------------------------------------------------- /Easy/van-eck.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | int A1, N; 6 | std::cin >> A1 >> N; std::cin.ignore(); 7 | 8 | std::vector dt (N,-1), sq (N, 0); 9 | 10 | sq[0] = A1; 11 | for (int i = 0; i < N ; i++ ) 12 | { 13 | if ( dt[sq[i]] >= 0 ) { sq[i+1] = i - dt[sq[i]]; } 14 | dt[sq[i]] = i; 15 | } 16 | 17 | std::cout << sq[N-1] << std::endl; 18 | } -------------------------------------------------------------------------------- /Easy/vectors-in-variables-dimensions.py: -------------------------------------------------------------------------------- 1 | import re 2 | import math 3 | 4 | pattern = r'(.+)\(([^)]+)\)' 5 | d = int(input()) 6 | n = int(input()) 7 | v = {} 8 | 9 | for i in range(n): 10 | match = re.match(pattern, input()) 11 | v[match.group(1)] = tuple(map(int, match.group(2).split(','))) 12 | 13 | NAME = "name" 14 | VAL = "val" 15 | DIST = "dist" 16 | 17 | min_result = { NAME:"", VAL:(), DIST:float('inf') } 18 | max_result = { NAME:"", VAL:(), DIST:0. } 19 | 20 | for k1,v1 in v.items(): 21 | for k2,v2 in v.items(): 22 | if k2 == k1: 23 | continue 24 | name = f"{k1}{k2}" 25 | val = tuple(y - x for x, y in zip(v1, v2)) 26 | dist = math.sqrt(sum(x**2 for x in val)) 27 | 28 | if dist < min_result[DIST]: 29 | min_result = {NAME: name, VAL: val, DIST: dist} 30 | if dist > max_result[DIST]: 31 | max_result = {NAME: name, VAL: val, DIST: dist} 32 | 33 | print('{}({})'.format(min_result[NAME], ','.join(map(str, min_result[VAL])))) 34 | print('{}({})'.format(max_result[NAME], ','.join(map(str, max_result[VAL])))) -------------------------------------------------------------------------------- /Easy/video-comments.py: -------------------------------------------------------------------------------- 1 | # Inspired from Carlwash's solution 2 | 3 | def S(com): 4 | if not hasattr(S, "prio"): 5 | S.prio = dict(Pinned=2, Followed=1, none=0) 6 | _, time, likes, pri = com[0].split('|') 7 | return S.prio[pri], int(likes), time 8 | 9 | coms = [] 10 | for _ in range(int(input())): 11 | obj = input(), [] 12 | if obj[0].startswith(' '): 13 | coms[-1][1].append(obj) 14 | else: 15 | coms.append(obj) 16 | 17 | for c, reps in sorted(coms, key=S, reverse=True): 18 | print(c) 19 | for r, _ in sorted(reps, key=S, reverse=True): 20 | print(r) 21 | -------------------------------------------------------------------------------- /Easy/walk-on-a-die.rs: -------------------------------------------------------------------------------- 1 | use std::collections::HashMap; 2 | use std::io; 3 | 4 | fn read_string() -> String { 5 | let mut input_line = String::new(); 6 | io::stdin().read_line(&mut input_line).unwrap(); 7 | input_line.trim_matches('\n').to_string() 8 | } 9 | 10 | fn main() { 11 | 12 | let mut rotations: HashMap> = HashMap::new(); 13 | rotations.insert('U', vec![4, 1, 0, 3, 5, 2]); 14 | rotations.insert('L', vec![4, 5, 1, 0, 3, 2]); 15 | rotations.insert('D', vec![4, 3, 5, 1, 0, 2]); 16 | rotations.insert('R', vec![4, 0, 3, 5, 1, 2]); 17 | 18 | let mut die = Vec::new(); 19 | for _ in 0..3 { 20 | die.extend( 21 | read_string() 22 | .trim_matches(' ').chars() 23 | .map(|x| x.to_digit(10).unwrap() as i32) 24 | ); 25 | } 26 | 27 | for command in read_string().chars() { 28 | if let Some(pi) = rotations.get(&command) { 29 | let next_die: Vec = pi.iter() 30 | .map(|&i| die[i]) 31 | .collect(); 32 | die = next_die; 33 | } 34 | } 35 | 36 | println!("{}", die[2]); 37 | } -------------------------------------------------------------------------------- /Easy/whats-so-complex-about-mandelbrot.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() { 4 | double _a,_b; scanf("%lf %lfi\n",&_a,&_b); 5 | int m; scanf("%d", &m); 6 | 7 | double ra=0, rb=0; 8 | for (int n = 1 ; n < m ; n++) { 9 | double tmp = rb*rb; 10 | rb = 2*ra*rb + _b; 11 | ra = ra*ra-tmp + _a; 12 | if ( (ra*ra + rb*rb) > 4.0) { m = n; break; } 13 | } 14 | printf("%d\n",m); 15 | } -------------------------------------------------------------------------------- /Easy/wheres-wally.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef std::vector Img; 4 | int 5 | main() 6 | { 7 | int wally_width, wally_height, pic_width, pic_height; 8 | 9 | std::cin >> wally_width >> wally_height; std::cin.ignore(); 10 | Img wally(wally_height, std::string()); 11 | for ( auto& line : wally ) 12 | getline(std::cin, line); 13 | 14 | 15 | std::cin >> pic_width >> pic_height; std::cin.ignore(); 16 | Img pic(pic_height, std::string()); 17 | for ( auto& line : pic ) 18 | getline(std::cin, line); 19 | 20 | bool match{ false }; 21 | for (int y = 0; y <= pic_height - wally_height && !match; y++) 22 | for (int pic_x = 0; pic_x <= pic_width - wally_width && !match; ++pic_x) 23 | { 24 | match = true; 25 | for (int wally_y = 0; wally_y < wally_height && match; wally_y++) 26 | { 27 | for (int wally_x = 0; wally_x < wally_width && match; wally_x++) 28 | { 29 | if (!isspace(wally[wally_y][wally_x]) && wally[wally_y][wally_x] != pic[y + wally_y][pic_x + wally_x]) 30 | { 31 | match = false; 32 | } 33 | } 34 | } 35 | 36 | if (match) 37 | { 38 | std::cout << pic_x << " " << y << "\n"; 39 | return EXIT_SUCCESS; 40 | } 41 | } 42 | } -------------------------------------------------------------------------------- /Easy/wordle-colorizer.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | std::string solve(std::string_view s, std::string_view answer) noexcept { 4 | 5 | enum class EValState : char { 6 | ABSENT = 'X', MISPLACED = 'O', CORRECT = '#' 7 | }; 8 | 9 | std::string ret(std::size(answer), static_cast(EValState::ABSENT)); 10 | 11 | if ( std::size(s) != std::size(answer) ) 12 | return ret; 13 | 14 | std::map occCount, occInAnswer; 15 | for ( const auto& c : answer ) ++occInAnswer[c]; 16 | 17 | for ( auto i{ 0 }; i < std::size(answer); ++i ) { 18 | const auto& curChar{ s.at(i) }; 19 | 20 | if ( curChar != answer.at(i) ) 21 | continue; 22 | 23 | ret[i] = static_cast(EValState::CORRECT); 24 | ++occCount[curChar]; 25 | } 26 | 27 | for ( auto i{ 0 }; i < std::size(answer); ++i ) { 28 | const auto& curChar{ s.at(i) }; 29 | 30 | if ( curChar == answer.at(i) || occCount[curChar] >= occInAnswer[curChar]) 31 | continue; 32 | 33 | ret[i] = static_cast(EValState::MISPLACED); 34 | ++occCount[curChar]; 35 | } 36 | 37 | return ret; 38 | } 39 | 40 | int main() 41 | { 42 | std::string answer, attempt; 43 | getline(std::cin, answer); 44 | 45 | std::cin.ignore(std::numeric_limits::max(), '\n'); 46 | 47 | while ( getline(std::cin, attempt) ) 48 | std::cout << solve(attempt, answer) << '\n'; 49 | } -------------------------------------------------------------------------------- /Easy/xml-mdf-2016.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | main() { 8 | string str; getline(cin, str); 9 | float c_depth(0), res_val(0); char res_c; 10 | map< char, float > weights; 11 | 12 | for ( auto it = str.begin(); it != str.end(); it++ ) 13 | if ( *it == '-' ) { c_depth--; it++; } 14 | else { c_depth++; weights[*it] += 1/c_depth; } 15 | 16 | for ( auto c : weights ) 17 | if (( c.second > res_val ) || (( c.second == res_val ) && (c.first < res_c)) ) { res_val = c.second; res_c = c.first; } 18 | cout << res_c << endl; 19 | } -------------------------------------------------------------------------------- /Easy/zeckendorf-representation-part-i.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | long long fib(long long num) noexcept { 4 | if ( 1 >= num ) return num; 5 | 6 | long long i{ 0 }, j{ 1 }, tmp{ 0 }; 7 | while ( j <= num ) { tmp = i, i = j, j += tmp; } 8 | return i; 9 | } 10 | 11 | int main() { 12 | long long input, cur; 13 | std::list zeckendorf{}; 14 | 15 | std::cin >> input; std::cin.ignore(); 16 | 17 | while ( 0 < input ) { 18 | cur = fib( input ); 19 | zeckendorf.push_back(cur); 20 | input -= cur; 21 | } 22 | 23 | std::stringstream ss; 24 | std::string output; 25 | for ( const auto& elm : zeckendorf ) { ss << elm << '+'; } 26 | output = ss.str(); 27 | if ( output.ends_with('+') ) { output.pop_back(); } 28 | std::cout << output << std::endl; 29 | } 30 | -------------------------------------------------------------------------------- /Easy/zhiwei-sun-squares.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n, cmpt{0}, sq; 6 | std::cin >> n; std::cin.ignore(); 7 | 8 | for ( int b = 0, sq = std::floor( std::sqrt(n) ); b <= sq; ++b ) 9 | for ( int c = 0; c <= sq; ++c ) 10 | for ( int d = 0; d <= sq; ++d ) { 11 | int tmp(n-(b*b + c*c + d*d)); 12 | if ( tmp < 0 ) break; 13 | double a( std::sqrt(tmp) ), e(std::sqrt(b+3*c+5*d)); 14 | if ( std::floor(a) == a && std::floor(e) == e ) ++cmpt; 15 | } 16 | 17 | std::cout << cmpt << "\n"; 18 | } -------------------------------------------------------------------------------- /Hard/blunder-episode-2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | #define EXIT -1 8 | 9 | struct Room { 10 | int id, money, top, right; 11 | }; 12 | 13 | static vector rooms; 14 | static vector results_memoized; 15 | 16 | int DFS(int index) 17 | { 18 | if (results_memoized[index] != -1) 19 | return results_memoized[index]; 20 | 21 | Room& c { rooms[index] }; 22 | int result{ c.money }; 23 | 24 | if (c.top != EXIT && c.right != EXIT) { 25 | result = c.money + max(DFS(c.top), DFS(c.right)); 26 | } 27 | else { 28 | if (c.top != EXIT) { result = c.money + DFS(c.top); } 29 | else if (c.right != EXIT) { result = c.money + DFS(c.right); } 30 | } 31 | 32 | results_memoized[index] = result; 33 | return result; 34 | } 35 | 36 | int main() 37 | { 38 | int N; 39 | cin >> N; cin.ignore(); 40 | 41 | rooms = vector(N, {-1, 0, EXIT, EXIT }); 42 | results_memoized = vector (N, -1); 43 | 44 | for (int i = 0; i < N; ++i) { 45 | string edgeT, edgeR; 46 | Room& r = rooms[i]; 47 | cin >> r.id >> r.money >> edgeT >> edgeR; 48 | 49 | if (edgeT != "E") r.top = stoi(edgeT); 50 | if (edgeR != "E") r.right = stoi(edgeR); 51 | } 52 | 53 | cout << DFS(0) << endl; 54 | } -------------------------------------------------------------------------------- /Hard/cgx-formatter.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | main() { 5 | int i_ind(0), n; 6 | bool i_str(false), i_line(true); 7 | cin >> n >> noskipws; 8 | 9 | for (char c; cin >> c; ) { 10 | if ( i_str ) { i_str = (c != '\''); cout << c; } 11 | else if ( c == '(' ) { 12 | if (!i_line) cout << endl; 13 | cout << string(i_ind, ' ') << c << endl; 14 | i_ind+= 4; i_line = true; 15 | } 16 | else if ( c == ')' ) { 17 | if (!i_line) cout << endl; 18 | i_ind-= 4; i_line = false; 19 | cout << string(i_ind, ' ') << c; 20 | } 21 | else if ( c == '\'' ) { 22 | cout << string(i_line * i_ind, ' ') << c; 23 | i_str = true; i_line = false; 24 | } 25 | else if ( c == ';' ) { cout << c << endl; i_line = true; } 26 | else if (string(" \t\n").find(c) == string::npos) { cout << string(i_line * i_ind, ' ') << c; i_line = false; } 27 | } 28 | } -------------------------------------------------------------------------------- /Hard/levenshtein-distance.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int levenshteinDistance(const std::string& s1, const std::string& s2) { 4 | std::vector< std::vector > m( s2.size() + 1, 5 | std::vector(s1.size() + 1, 0) ); 6 | 7 | for ( int i = 1; i <= s1.size(); i++ ) { m[0][i] = i; } 8 | for ( int j = 1; j <= s2.size(); j++ ) { m[j][0] = j; } 9 | 10 | for ( int i = 1; i <= s1.size(); i++ ) 11 | for ( int j = 1; j <= s2.size(); j++ ) { 12 | int subCost = (s1[i-1] == s2[j-1]) ? 0 : 1; 13 | m[j][i] = std::min( subCost + m[j-1][i-1], 14 | std::min( 1 + m[j-1][i], 1 + m[j][i-1] ) ); 15 | } 16 | return m[s2.size()][s1.size()]; 17 | } 18 | 19 | int main() { 20 | std::string w1,w2; 21 | getline(std::cin, w1); 22 | getline(std::cin, w2); 23 | std::cout << levenshteinDistance(w1, w2 ) << std::endl; 24 | } -------------------------------------------------------------------------------- /Hard/max-rect.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int H, W; 5 | 6 | int maxSum1D(int* arr, int* st, int* end ) { 7 | int sum = 0, l_st = 0, res = INT_MIN; *end = -1; 8 | 9 | for (int i = 0; i < H; ++i) { 10 | sum += arr[i]; 11 | if (sum < 0 ) { sum = 0; l_st = i+1; } 12 | else if (sum > res) { res = sum; *st = l_st; *end = i; } 13 | } 14 | 15 | if (*end != -1) return res; 16 | 17 | res = arr[0]; *st = *end = 0; 18 | for (int i = 1; i < H; i++) if (arr[i] > res) { res = arr[i]; *st = *end = i; } 19 | return res; 20 | } 21 | 22 | int maxSum2D(int c[101][101]) { 23 | int res = INT_MIN, l_lft, l_rht, l_top, l_bot; 24 | int left, right, sum, start, finish; 25 | 26 | for (left = 0; left < W; ++left) { 27 | int tmp[H] = {0}; 28 | 29 | for (right = left; right < W; ++right) { 30 | for (int i = 0; i < H; ++i) { tmp[i] += c[i][right]; } 31 | 32 | sum = maxSum1D(tmp, &start, &finish); 33 | if (sum > res) { res = sum; l_lft = left; l_rht = right; l_top = start; l_bot = finish; } 34 | } 35 | } 36 | return res; 37 | } 38 | 39 | main() { 40 | int arr[101][101]; 41 | scanf("%d%d", &W, &H); fgetc(stdin); 42 | for (int i = 0; i < H; i++) 43 | for (int j = 0; j < W; j++) { scanf("%d", &arr[i][j]); } 44 | 45 | printf("%d\n", maxSum2D(arr) ); 46 | } -------------------------------------------------------------------------------- /Medium/10101.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | char arr[11][11]; 4 | int W, H, res = 0; 5 | 6 | void check_row(int c, int *r) { 7 | int res = 0; 8 | for(int i = 0; i < W; i++) { if(arr[c][i] == '.') { res++; } } 9 | if(res <= 2){ (*r)++; } 10 | } 11 | 12 | void check_col(int c, int *r) { 13 | int l_res = 0; 14 | for(int i = 0; i < H; i++) { if(arr[i][c] == '.') { l_res++; } } 15 | if(l_res <= 2){ (*r)++; } 16 | } 17 | 18 | main() { 19 | scanf("%d%d", &W, &H); fgetc(stdin); 20 | for (int i = 0; i < H; i++) { scanf("%s",arr[i]); fprintf(stderr, "%s\n", arr[i]); } 21 | 22 | for (int i = 0; i < H-1; i++) 23 | for (int j = 0; j < W-1; j++) 24 | if( arr[i ][j ] == '.' && arr[i ][j+1] == '.' && 25 | arr[i+1][j ] == '.' && arr[i+1][j+1] == '.' ) { 26 | int l_res = 0; 27 | check_row(i, &l_res); check_row(i+1, &l_res); 28 | check_col(j, &l_res); check_col(j+1, &l_res); 29 | if(l_res > res) { res = l_res; } 30 | } 31 | printf("%d", res); 32 | } -------------------------------------------------------------------------------- /Medium/ancestors-&-descendants.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void test_empty(vector& data) { 8 | if ( !data.empty() ) { 9 | cout << data[0]; 10 | for ( int i = 1; i < data.size(); i++ ) { cout << " > " << data[i]; } 11 | cout << endl; 12 | } 13 | } 14 | 15 | int main() { 16 | int pts, n; cin >> n; cin.ignore(); 17 | vector stack; 18 | string tmp; 19 | 20 | for (int i = 0; i < n && getline(cin, tmp); i++) { 21 | pts = tmp.rfind("."); 22 | pts = (pts == string::npos) ? 0 : ++pts; 23 | 24 | if( pts >= stack.size() ) { stack.push_back( tmp.substr(pts) ); } 25 | else { 26 | test_empty(stack); 27 | stack.erase( stack.begin()+pts, stack.end() ); 28 | stack.push_back( tmp.substr(pts) ); 29 | } 30 | } 31 | test_empty(stack); 32 | } -------------------------------------------------------------------------------- /Medium/aneo.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct _light { int dst, tim; } light; 5 | 6 | main() { 7 | int max, lCount; scanf("%d%d", &max, &lCount); 8 | light lght[lCount]; 9 | 10 | for (int i = 0; i < lCount; i++) { scanf("%d%d", &lght[i].dst, &lght[i].tim); } 11 | 12 | do{ 13 | int isOk = 1; 14 | for (int i = 0; i < lCount; i++) 15 | if ( (int)floor((3.6*lght[i].dst/max)/lght[i].tim)%2 != 0 ) { isOk = 0; break; } 16 | if (isOk) { printf("%d", max); break; } 17 | } while ( max-- ); 18 | } -------------------------------------------------------------------------------- /Medium/ascii-art-glass-stacking.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() { 4 | int N, fl = 1, tmp = 0; scanf("%d", &N); 5 | char pd[1000], * pt[] = { " *** ", 6 | " * * ", 7 | " * * ", 8 | "*****" }; 9 | 10 | while( (tmp += fl) <= N ) { fl++; } --fl; 11 | 12 | for ( int i = 1; i <= fl; i++ ) 13 | for ( int j = 0; j < 4; j++ ) { 14 | memset(pd, ' ', (fl - i)*3); pd[(fl - i)*3] = 0; 15 | printf("%s", pd); 16 | for ( int t = 0; t < i; t++ ) { 17 | printf("%s", pt[j]); 18 | if( t < i -1 ) { putchar(' '); } 19 | } 20 | printf("%s\n", pd); 21 | } 22 | } -------------------------------------------------------------------------------- /Medium/ascii-graph.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MIN(a,b)((a= y_min; i-- ) { 27 | for ( int j = x_min; j <= x_max; j++ ) { 28 | char curr = '.'; 29 | if ( i == 0 && j == 0 ) { curr = '+'; } 30 | else if ( i == 0 ) { curr = '-'; } 31 | else if ( j == 0 ) { curr = '|'; } 32 | 33 | if ( find_pt(j,i) == 1 ) { curr = '*'; } 34 | putchar(curr); 35 | } 36 | printf("\n"); 37 | } 38 | } -------------------------------------------------------------------------------- /Medium/bag-of-balls.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | typedef long long int lld; 8 | 9 | void getFactors (lld num, vector& vec) { 10 | if (num != 1) { vec.push_back(num); } 11 | for (int i = 2; i <= sqrt( static_cast(num) ); i++) 12 | if (num%i == 0) { vec.push_back(i); vec.push_back(num/i); } 13 | } 14 | 15 | void simplifyFun(lld& a, lld& b) { 16 | lld tempN = a, tempD = b, small, temp; 17 | vector vec; 18 | if (tempN == tempD ) { a = 1; b = 1; return ; } 19 | else if (tempN == -tempD) { a = -1; b = 1; return ; } 20 | else if (tempN == 0 ) { b = 1; return ; } 21 | 22 | small = (abs(tempN) < abs(tempD)) ? abs(tempN) : abs(tempD); 23 | 24 | getFactors(small, vec); 25 | for (int i = 0; i < vec.size(); i++) { 26 | temp = vec[i]; 27 | while (tempN%temp == 0 && tempD%temp == 0) { tempN /= temp; tempD /= temp; } 28 | } 29 | a = tempN; b = tempD; 30 | } 31 | 32 | lld bin( int n, int k) { 33 | n -= k; double c = 1; 34 | for (int i = 1; i <= k; i++) { c = c * (n + i) / i; } 35 | return c; 36 | } 37 | 38 | main() { 39 | int N, W, s, k; 40 | cin >> N >> W >> s >> k; cin.ignore(); 41 | 42 | lld a = (bin(W,k) * bin(N-W, s-k)), b = bin(N,s); 43 | simplifyFun(a, b); 44 | if ( a == b ) cout << "1:0" << endl; 45 | else cout << a << ":" << (b - a) << endl; 46 | } -------------------------------------------------------------------------------- /Medium/binary-sequence.py: -------------------------------------------------------------------------------- 1 | for _ in range( int(input())): 2 | i = int(input(), 2) 3 | if i == 0: 4 | print('0') 5 | else: 6 | i -= 1 7 | l = 1 8 | while i >= l * 2**(l-1): 9 | i -= l * 2**(l-1) 10 | l += 1 11 | n, i = divmod(i, l) 12 | n += 2**(l-1) 13 | print(f'{n:b}'[i]) 14 | -------------------------------------------------------------------------------- /Medium/bit-count-to-limit.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | uint32_t n, rL{0}, rP{0}, ret{0}; 6 | std::cin >> n; 7 | 8 | while ( n ) { 9 | if ( n & 1 ) { 10 | ret += rL << (rL -1); 11 | ret += rP + 1; 12 | rP |= 1 << rL; 13 | } 14 | n >>= 1; 15 | ++rL; 16 | } 17 | 18 | std::cout << ret << std::endl; 19 | } -------------------------------------------------------------------------------- /Medium/bouncing-barry.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections.Generic; 4 | 5 | class Solution 6 | { 7 | static void Main() 8 | { 9 | var dirs = Console.ReadLine().Split(" ").ToList(); 10 | var nbs = Console.ReadLine().Split(" ").Select(int.Parse).ToList(); 11 | var moves = new (int, int)[] {(0, 1), (0, -1), (1, 0), (-1, 0)}; 12 | 13 | var on = new HashSet<(int, int)>(); 14 | (int, int) pos = (0, 0); 15 | 16 | for (int dir = 0; dir < dirs.Count; dir++) { 17 | for (int i = 0; i < nbs[dir]; i++) { 18 | var vec = moves["NSEW".IndexOf(dirs[dir])]; 19 | pos = (pos.Item1 + vec.Item1, pos.Item2 + vec.Item2); 20 | 21 | if (on.Contains(pos)) on.Remove(pos); 22 | else on.Add (pos); 23 | } 24 | } 25 | 26 | if (on.Count == 0) { 27 | Console.WriteLine("."); 28 | return; 29 | } 30 | 31 | int xMin = on.Min(a => a.Item1), xMax = on.Max(a => a.Item1), 32 | yMin = on.Min(a => a.Item2), yMax = on.Max(a => a.Item2); 33 | 34 | for (int i = yMax; i >= yMin; i--) { 35 | for (int j = xMin; j <= xMax; j++) 36 | Console.Write(on.Contains((j, i)) ? "#" : "."); 37 | Console.WriteLine(); 38 | } 39 | } 40 | } -------------------------------------------------------------------------------- /Medium/box-of-cigars.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int N, a[1000], res = 0, tmp_res = 0; 6 | 7 | void check(int j, int d) { 8 | for(int i = j+1; i < N; i++) { 9 | int tmp = a[i]-a[j]; 10 | if ( tmp == d ) { tmp_res++; check(i, d); } 11 | else if ( tmp > d ) { return; } 12 | } 13 | } 14 | 15 | void removeDuplicates() { 16 | int temp[N], j = 0; 17 | for (int i = 0; i< N-1; i++) if (a[i] != a[i+1]) { temp[j++] = a[i]; } 18 | temp[j++] = a[N-1]; 19 | for (int i=0; i res ) { res = tmp_res; } 31 | } 32 | printf("%d\n", res); 33 | } -------------------------------------------------------------------------------- /Medium/brackets-enhanced-edition.js: -------------------------------------------------------------------------------- 1 | const data = [...new Array(+readline())].map(() => readline().split('')); 2 | const test = (s, a) => { 3 | switch (a) { 4 | case '(': case ')': (s[s.length-1] === '(') ? s.pop() : s.push('('); break; 5 | case '[': case ']': (s[s.length-1] === '[') ? s.pop() : s.push('['); break; 6 | case '{': case '}': (s[s.length-1] === '{') ? s.pop() : s.push('{'); break; 7 | case '<': case '>': (s[s.length-1] === '<') ? s.pop() : s.push('<'); break; 8 | } 9 | return s; 10 | }; 11 | 12 | data.forEach( (data) => { console.log(data.reduce(test, []).length === 0); }); -------------------------------------------------------------------------------- /Medium/brackets-extended-edition.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | const char *e; 4 | 5 | int t(char a, char b) { 6 | char c = *e++; 7 | if ( c == a || c == b ) return 1; 8 | switch(c) { 9 | case '(' : case ')' : return t('(',')') && t(a, b); 10 | case '[' : case ']' : return t('[',']') && t(a, b); 11 | case '{' : case '}' : return t('{','}') && t(a, b); 12 | case '<' : case '>' : return t('<','>') && t(a, b); 13 | case 0 : return 0; 14 | default : return t(a, b); 15 | } 16 | } 17 | 18 | main() { 19 | int N; scanf("%d", &N); 20 | char expr[10001]; 21 | while ( scanf("%s", expr) == 1 ) { e = expr; printf(t(0,0) ? "true\n" : "false\n"); } 22 | } -------------------------------------------------------------------------------- /Medium/brackets-ultimate-edition.js: -------------------------------------------------------------------------------- 1 | const exprs = [...Array(+readline())].map(() => readline().match(/[\(\)\[\]\{\}\<\>]/g).join('')); 2 | const reg = [/\(\)|\{\}|\[\]|<>/g, /([(){}[\]<>])\1/, /\)\(|\}\{|\]\[|> { 5 | let sum = 0; 6 | for (let i = 0; i < reg.length; ++i) { 7 | const r = expr.replace(reg[i], ''); 8 | if (r !== expr) { expr = r; sum += i; i = -1; } 9 | } 10 | console.log(expr.length ? -1 : sum); 11 | }); -------------------------------------------------------------------------------- /Medium/bruce-lee.js: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | import java.math.*; 4 | 5 | class Solution { 6 | 7 | public static void main(String args[]) { 8 | Scanner in = new Scanner(System.in); 9 | String st = ""; 10 | while (in.hasNext()) { 11 | try { 12 | String tmp = in.next(); 13 | int num = in.next().length(); 14 | int bin = tmp.equals("0") ? 1 : 0; 15 | 16 | if (tmp.equals("000")) {System.out.println("INVALID"); return; } 17 | for (int i = 0; i < num; i++) {st += ""+bin; } 18 | } 19 | catch (Exception e) {System.out.println("INVALID"); return;} 20 | } 21 | if (st.length() % 7 != 0) {System.out.println("INVALID"); return;} 22 | String res = ""; 23 | while (st.length() > 0) { 24 | String cur = st.substring(0,7); 25 | st = st.substring(7); 26 | char cnt = (char)Integer.parseInt("0"+cur,2); 27 | res += cnt; 28 | } 29 | System.out.println(res); 30 | } 31 | } -------------------------------------------------------------------------------- /Medium/bulgarian-solitaire.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | std::istream_iterator it(std::cin), eos; 6 | std::vector v(++it, eos); 7 | std::vector< std::vector > save; 8 | 9 | while ( true ) { 10 | v.erase( std::remove( std::begin(v), std::end(v), 0 ), std::end(v) ); 11 | std::sort( std::begin(v), std::end(v) ); 12 | 13 | if ( auto it = std::find( std::begin(save), std::end(save), v); it != std::end(save) ) { 14 | std::cout << std::size(save) - std::distance( std::begin(save), it ) << "\n"; 15 | break; 16 | } 17 | 18 | save.emplace_back(v); 19 | std::for_each( std::begin(v), std::end(v), [](auto& num){ --num; }); 20 | v.push_back( std::size(v) );; 21 | } 22 | } -------------------------------------------------------------------------------- /Medium/bulls-and-cows.c: -------------------------------------------------------------------------------- 1 | // Solution from SatineChatounette 2 | 3 | #include 4 | 5 | int check(int g1,int g2,int b,int c) 6 | { 7 | int g1c[] = { g1%10, (g1/10)%10, (g1/100)%10, (g1/1000)%10 }; 8 | int g2c[] = { g2%10, (g2/10)%10, (g2/100)%10, (g2/1000)%10 }; 9 | int nbb=0, nbc=0; 10 | int taken[2][4] = { { 0, 0, 0, 0 }, { 0, 0, 0, 0 } }; 11 | for(int i=0;i<4;++i) { 12 | if(g1c[i]==g2c[i]) { 13 | taken[0][i] = taken[1][i] = 1; 14 | ++nbb; 15 | } 16 | } 17 | if(nbb!=b) return 0; 18 | for(int i=0;i<4;++i) { 19 | if(taken[0][i]) continue; 20 | for(int j=0;j<4;++j) { 21 | if(j==i||taken[1][j]) continue; 22 | if(g1c[i]==g2c[j]) { 23 | taken[0][i] = taken[1][j] = 1; 24 | ++nbc; 25 | break; 26 | } 27 | } 28 | } 29 | return (nbc==c); 30 | } 31 | 32 | int main() 33 | { 34 | int N; 35 | scanf("%d", &N); 36 | int guesses[100][3]; 37 | for(int i=0;i 2 | #include 3 | 4 | typedef struct _radar { char imm[8]; int d; long ts; } radar; 5 | 6 | main() { 7 | int L, N, d, nb = 0; scanf("%d%d", &L, &N); fgetc(stdin); 8 | radar r[N], c; 9 | char tmp[256], *it; 10 | for (int i = 0; i < N && fgets(tmp, 256, stdin); i++) { 11 | it = strtok(tmp, " "); 12 | memmove(c.imm, it, sizeof(it)); 13 | c.d = atoi( strtok(NULL, " ") ); 14 | c.ts = atol( strtok(NULL, " ") ); 15 | 16 | if ( i > 0 && !strcmp(c.imm, r[i-1].imm) && (3600.f*(c.d - r[i-1].d)/(c.ts - r[i-1].ts) > L) ) { 17 | nb++; printf("%s %d\n", c.imm, c.d); 18 | } 19 | r[i] = c; 20 | } 21 | if(nb == 0) printf("OK\n"); 22 | } -------------------------------------------------------------------------------- /Medium/byte-pair-encoding.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | n, m = [int(i) for i in input().split()] 4 | inStr = ''.join(input() for i in range(n)) 5 | 6 | nt = list('ZYXWVUTSRQPONMLKJIHGFEDCBA') 7 | freqs = defaultdict(list) 8 | rules = [] 9 | 10 | while True: 11 | freqs.clear() 12 | for i in range(len(inStr) - 1): 13 | key = inStr[i : i + 2] 14 | if i and freqs[key] and freqs[key][-1] >= i - 1: 15 | continue 16 | freqs[key].append(i) 17 | 18 | dom = max(freqs, key=lambda p: len(freqs[p])) 19 | if len(freqs[dom]) == 1: 20 | break 21 | 22 | t = nt.pop(0) 23 | inStr = inStr.replace(dom, t) 24 | rules.append((t, dom)) 25 | 26 | print(inStr) 27 | for rule in rules: 28 | print("{} = {}".format(*rule)) -------------------------------------------------------------------------------- /Medium/cards-castle.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int H, W; 5 | char S[30][129]; 6 | 7 | bool stable (int i, int j) { 8 | switch (S[j][i]) { 9 | case '/' : return (i != W-1 && S[j ][i+1] == '\\') && 10 | (j == H-1 || S[j+1][i ] == '\\'); 11 | case '\\': return (i != 0 && S[j ][i-1] == '/' ) && 12 | (j == H-1 || S[j+1][i ] == '/' ); 13 | } 14 | return true; 15 | } 16 | 17 | main() { 18 | scanf("%d", &H); fgetc(stdin); 19 | W = H * 2; 20 | for (int i = 0; i < H; i++) { fgets(S[i], 129, stdin); } 21 | for (int i = 0; i < H; i++) 22 | for (int j = 0; j < W; j++) 23 | if (!stable(j, i) ) { printf("UNSTABLE\n"); exit(0); } 24 | printf("STABLE\n"); 25 | } -------------------------------------------------------------------------------- /Medium/carmichael-numbers.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int gcd(int i1, int i2) { 5 | if( i1 < i2 ) return gcd(i2, i1); 6 | if( i1 % i2 == 0) return i2; 7 | return gcd( i2, i1%i2); 8 | } 9 | 10 | int pw(int i1, int i2, int mod) { 11 | if ( i2 == 0 ) return 1; 12 | long t = pw(i1, i2/2, mod) % mod; 13 | t = (t * t) % mod; 14 | if (i2 % 2 == 1) { t = (t * i1) % mod; } 15 | return t; 16 | } 17 | 18 | bool check(int n) { 19 | bool prime = true; 20 | for (int a = 2; a < n; a++) 21 | if (gcd(n, a) == 1) { 22 | if (pw(a, n, n) != a) { return false; } 23 | } else { prime = false; } 24 | return !prime; 25 | } 26 | 27 | main() { 28 | int n; scanf("%d", &n); 29 | printf("%s\n", check(n)?"YES":"NO"); 30 | } -------------------------------------------------------------------------------- /Medium/cgfunge-interpreter.py: -------------------------------------------------------------------------------- 1 | # From User "MMMAAANNN" 2 | 3 | DIR = (1, 0), (-1, 0), (0, 1), (0, -1) 4 | out, direct, stack = '', DIR[0], [] 5 | x = y = smode = value = 0 6 | grid = tuple(input() for i in range(int(input()))) 7 | while smode or value is not 'E': 8 | value, jump = grid[y][x], 1 9 | if value in '"': smode = not smode 10 | elif value.isdigit() or smode: stack += [(int, ord)[smode](value)] 11 | elif value in '+-*': stack += [eval(str(stack.pop(-2)) + value + str(stack.pop()))] 12 | elif value in 'X': stack += [stack.pop(), stack.pop()] 13 | elif value in 'D': stack += [stack[-1]] 14 | elif value in 'P': stack.pop() 15 | elif value in 'IC': out += (str, chr)[value is 'C'](stack.pop()) 16 | elif value in '> 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | string in, out, tmp; 10 | char repl = '`'; 11 | 12 | int main() { 13 | map repl_map; 14 | int N; cin >> N; cin.ignore(); 15 | for (int i = 0; i < N && getline(cin, tmp); i++) { in += tmp; } 16 | for (int i = 0; i < in.size(); i++) { 17 | char c = in[i]; 18 | if ( c == '$' ) { 19 | string t; 20 | out.push_back(c); 21 | do { i++; t.push_back(in[i]); } while( in[i] != '$' ); 22 | if(repl_map.find(t) == repl_map.end()) {repl_map[t] = ++repl;} 23 | out.push_back(repl_map[t]); 24 | out.push_back(c); 25 | } 26 | else if ( c == '\'' ) { 27 | out.push_back(c); 28 | do { i++; out.push_back(in[i]); } while( in[i] != '\'' ); 29 | } 30 | else { 31 | switch(in[i]) { 32 | case ' ' : case '\t': case '\n': break; 33 | default : out.push_back(in[i]); break; 34 | } 35 | } 36 | } 37 | cout << out << endl; 38 | } 39 | 40 | -------------------------------------------------------------------------------- /Medium/conway-sequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | vector Conwait_it(vector& p_data) 9 | { 10 | vector l_return; 11 | for (auto it = p_data.begin(); it != p_data.end(); ) 12 | { 13 | int l_cmpt = 0; 14 | for (auto it2 = it; it2 != p_data.end(); ++it2) 15 | { 16 | if(*it2 == *it) ++l_cmpt; 17 | else break; 18 | } 19 | l_return.push_back(l_cmpt); 20 | l_return.push_back(*it); 21 | it += l_cmpt; 22 | } 23 | return l_return; 24 | } 25 | 26 | int main() 27 | { 28 | int R, L; 29 | cin >> R; cin.ignore(); 30 | cin >> L; cin.ignore(); 31 | vector result(1, R); 32 | 33 | for(auto i = 0; i 2 | 3 | int R, C, res = 0; 4 | long found[1000] = {0}, grid[8][8] = {0}; 5 | 6 | int find(long val) { 7 | for (int i = 0; i < res; i++) { if(found[i] == val){ return 1; } } 8 | return 0; 9 | } 10 | 11 | void check(int x, int y) { 12 | long val = grid[x][y]; prime(val); 13 | for(int i = x+1; i < R; i++ ) { val = 10*val + grid[i][y]; prime(val); } 14 | val = grid[x][y]; 15 | for(int i = y+1; i < C; i++ ) { val = 10*val + grid[x][i]; prime(val); } 16 | } 17 | 18 | void prime(long val) { 19 | int tmp = 1; 20 | if (val < 2 || find(val) > 0 ) { return; } 21 | for (int i = 2; i <= sqrt(val); i++) { if ( val%i == 0 ) { tmp = 0; break; } } 22 | if (tmp == 1 ) { found[res++] = val; } 23 | } 24 | 25 | main() { 26 | scanf("%d%d", &R, &C); 27 | for (int i = 0; i < R; i++) 28 | for (int j = 0; j < C; j++) { scanf("%d", &grid[i][j]); } 29 | 30 | for(int i = 0; i < R; i++) 31 | for (int j = 0; j < C; j++) { check(i,j); } 32 | printf("%d\n", res); 33 | } -------------------------------------------------------------------------------- /Medium/counting-squares-on-pegs.js: -------------------------------------------------------------------------------- 1 | const pts = [...new Array(+readline())] 2 | .map((_) => { 3 | const [x, y] = readline().split(' ').map(Number); 4 | return {x: x, y: y}; 5 | }); 6 | 7 | let res = 0; 8 | 9 | for (let i = 0; i < pts.length-1; i++) { 10 | const p1 = pts[i]; 11 | for (let j = i+1; j < pts.length; j++) { 12 | const p2 = pts[j]; 13 | const dx = p2.x - p1.x; 14 | const dy = p2.y - p1.y; 15 | if ( 16 | (p1.x === p2.x && p1.y === p2.y) || 17 | (dx < 0 || dy < 0) || 18 | (!pts.some((e) => e.x === p2.x - dy && e.y === p2.y + dx)) || 19 | (!pts.some((e) => e.x === p1.x - dy && e.y === p1.y + dx) || 20 | (dx === 0 && p1.x - dy < p2.x) 21 | ) 22 | ) continue; 23 | res++; 24 | } 25 | } 26 | 27 | console.log(res); -------------------------------------------------------------------------------- /Medium/digit-sum-successor.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | void next(const vector& arr, const int& d) { 9 | vector a1, a2, a3, a4, res; 10 | int i = d-1,j = 0; 11 | while (arr[i] == 0 ) { a1.push_back(0); i--; } 12 | if (i >=0 ) { a2.push_back(arr[i]); i--; } 13 | if (!a2.empty() ) { a2[0]--; } 14 | while (i >=0 && arr[i] == 9) { a3.push_back(9); i--; } 15 | while (j <= i ) { a4.push_back(arr[j]); j++; } 16 | 17 | j = max(0, (int)a4.size()-1); 18 | if(a4.empty()) { a4.push_back(1); } 19 | else { a4[j]++; } 20 | 21 | for(auto c: a4 ) { res.push_back(c); } 22 | for(auto c: a1 ) { res.push_back(c); } 23 | for(auto c: a2 ) { res.push_back(c); } 24 | for(auto c: a3 ) { res.push_back(c); } 25 | for(auto c : res) { printf("%d", c); } 26 | } 27 | 28 | main() { 29 | long long N; scanf("%lld", &N); 30 | int d =0; 31 | vector v_N; 32 | while(N) { 33 | v_N.insert(v_N.begin(), N%10); 34 | N /= 10; d++; 35 | } 36 | next(v_N, d); 37 | } -------------------------------------------------------------------------------- /Medium/divide-the-factorial.rb: -------------------------------------------------------------------------------- 1 | require 'prime' 2 | a,b0=gets.split.map(&:to_i) 3 | p a.prime_division.map{|n,p| 4 | b=b0 5 | r=0 6 | while b>0 7 | r+=b/n 8 | b/=n 9 | end 10 | r/p 11 | }.min -------------------------------------------------------------------------------- /Medium/dominoes-path.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | int N, t_A, t_B; 7 | pair curr; 8 | vector< pair > dom; 9 | 10 | void check() { 11 | if(dom.empty()) return; 12 | for( int i= 0; i < dom.size(); i++ ) { 13 | pair t = dom[i]; 14 | if ( curr.first == t.first || curr.first == t.second || 15 | curr.second == t.first || curr.second == t.second ) { 16 | curr = t; 17 | dom.erase(dom.begin()+i); 18 | check(); 19 | } 20 | } 21 | } 22 | 23 | int main() { 24 | cin >> N; cin.ignore(); 25 | 26 | for (int i = 0; i < N && cin>>t_A>>t_B; i++) { dom.push_back( make_pair(t_A, t_B) ); } 27 | for (auto& i: dom) cerr << i.first << " : " << i.second << endl; 28 | curr = dom[0]; 29 | dom.erase(dom.begin()); 30 | check(); 31 | cout << ( dom.empty() ? "true" : "false" ) << endl; 32 | } -------------------------------------------------------------------------------- /Medium/dwarfs-standing-on-the-shoulders-of-giants.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | using namespace std; 9 | 10 | set roots; 11 | map< int, vector > vertexes; 12 | 13 | int countReferences(const int node) 14 | { 15 | int l_res = 1; 16 | if (vertexes[node].empty()) return l_res; 17 | else 18 | { 19 | for (int v : vertexes[node]) 20 | { 21 | int c = countReferences(v); 22 | if (c > l_res) l_res = c; 23 | } 24 | return l_res + 1; 25 | } 26 | } 27 | 28 | int main() 29 | { 30 | int n; // the number of relationships of influence 31 | int x, y; // a relationship of influence between two people (x influences y) 32 | int l_result(0); 33 | cin >> n; cin.ignore(); 34 | 35 | for (int i = 0; i < n; i++) { 36 | cin >> x >> y; cin.ignore(); 37 | 38 | roots.insert(x); 39 | vertexes[x].push_back(y); 40 | } 41 | 42 | for( const auto& it : vertexes ) 43 | for( auto& dest : it.second ) roots.erase( dest ); 44 | 45 | for (auto root : roots) 46 | { 47 | int c = countReferences(root); 48 | if (c > l_result) l_result = c; 49 | } 50 | 51 | cout << l_result << endl; 52 | } -------------------------------------------------------------------------------- /Medium/elementary-cellular-automaton.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int chartoInt(const char c) { return ((c == '@') ? 1 : 0); } 6 | char inttoChar(const int i) { return ((i == 1) ? '@' : '.'); } 7 | int getIndex(const char c1, const char c2, const char c3 ) { return 4*chartoInt(c1) + 2*chartoInt(c2) + chartoInt(c3); } 8 | 9 | void main() { 10 | int R, N, code[8]; 11 | char startPattern[51]; char tmpPattern[51]; 12 | scanf("%d%d%s", &R, &N, startPattern); 13 | 14 | for (int i = 0; i < 8; ++i) code[i] = ( R >> i ) & 1; 15 | 16 | while(N--) { 17 | printf("%s\n", startPattern); 18 | tmpPattern[0] = inttoChar(code[getIndex( startPattern[strlen(startPattern)-1], startPattern[0], startPattern[1] )]); 19 | for (int j = 1; j < strlen(startPattern)-1; ++j) { tmpPattern[j] = inttoChar(code[getIndex( startPattern[j-1], startPattern[j], startPattern[j+1] )]); } 20 | tmpPattern[strlen(startPattern)-1] = inttoChar(code[getIndex( startPattern[strlen(startPattern)-2], startPattern[strlen(startPattern)-1], startPattern[0]) ]); 21 | strcpy(startPattern, tmpPattern); 22 | } 23 | } -------------------------------------------------------------------------------- /Medium/entry-code.rs: -------------------------------------------------------------------------------- 1 | use std::io; 2 | 3 | macro_rules! parse_input { 4 | ($t:ident) => {{ 5 | let mut input_line = String::new(); 6 | io::stdin().read_line(&mut input_line).unwrap(); 7 | input_line.trim_matches('\n').parse::<$t>().unwrap() 8 | }} 9 | } 10 | 11 | // https://fr.wikipedia.org/wiki/Suite_de_de_Bruijn 12 | fn de_bruijn(k: u8, n: usize) -> String { 13 | let alphabet = ('0'..(k + b'0') as char).collect::>(); 14 | let mut a = vec![0; k as usize * n]; 15 | let mut sequence = vec![]; 16 | 17 | fn db(a: &mut [usize], sequence: &mut Vec, t: usize, p: usize, k: usize, n: usize) { 18 | if t > n { 19 | if 0 == n % p { 20 | sequence.extend(&a[1..p + 1]); 21 | } 22 | } else { 23 | a[t] = a[t - p]; 24 | db(a, sequence, t + 1, p, k, n); 25 | for j in a[t - p] + 1..k { 26 | a[t] = j; 27 | db(a, sequence, t + 1, t, k, n); 28 | } 29 | } 30 | } 31 | 32 | db(&mut a, &mut sequence, 1, 1, k as usize, n); 33 | sequence 34 | .into_iter() 35 | .map(|i| alphabet[i]) 36 | .collect::() 37 | } 38 | 39 | fn main() { 40 | let x = parse_input!(u8); 41 | let n = parse_input!(usize); 42 | 43 | println!("{}{}", de_bruijn(x, n), (0..n - 1).map(|_| '0').collect::()); 44 | } 45 | -------------------------------------------------------------------------------- /Medium/equalizing-arrays.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | template 4 | using V = std::vector; 5 | 6 | int main() 7 | { 8 | int N; std::cin >> N; 9 | V a1(N), a2(N); 10 | V>> movesVec(N); 11 | 12 | 13 | for ( auto& elm : a1 ) std::cin >> elm; 14 | for ( auto& elm : a2 ) std::cin >> elm; 15 | 16 | int curDiff{ 0 }, totalMoves{ 0 }; 17 | for ( auto i = 0; i < N; ++i ) { 18 | if ( curDiff ) { 19 | ++totalMoves; 20 | if ( curDiff > 0 ) movesVec[i ].emplace_back(-1, curDiff); 21 | else movesVec[i - 1].emplace_back( 1, -curDiff); 22 | } 23 | curDiff += a2[i] - a1[i]; 24 | } 25 | 26 | std::cout << totalMoves << "\n"; 27 | 28 | for ( int i = 0; i < N; ++i ) { 29 | while ( i >= 0 && !std::empty(movesVec[i]) ) { 30 | auto [D, V] = movesVec[i].front(); 31 | 32 | if (a1[i] < V) 33 | break; 34 | 35 | a1[i ] -= V; 36 | a1[i + D] += V; 37 | 38 | movesVec[i].pop_front(); 39 | 40 | std::cout << i-- + 1 << " " << D << " " << V << "\n"; 41 | } 42 | } 43 | } -------------------------------------------------------------------------------- /Medium/factorial-vs-exponential.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | main() { 4 | int K; scanf("%d", &K); 5 | for (int i = 0; i < K; i++) { 6 | int n = 0; float a; double f = 0; 7 | scanf("%f", &a); a = log10(a); 8 | while(1) { 9 | f += log10(++n); 10 | if( f > a*n ) { printf("%d%s", n, (i==K-1)?"":" "); break; } 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Medium/find-the-replacement.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() { 8 | map dic; 9 | string X, Y, Z; getline(cin, X); getline(cin, Y); 10 | 11 | if ( !X.compare(Y) ) { cout << "NONE" << endl; return 0; } 12 | else for( int c = 0; c < X.size(); c++ ) { 13 | if ( dic.find(X[c]) == dic.end() ) { dic[X[c]] = Y[c]; Z.push_back(X[c]); } 14 | else if( dic[X[c]] != Y[c] ) { cout << "CAN'T" << endl; return 0; } 15 | } 16 | for(auto i:Z) { if( i != dic[i]) cout << i << "->" << dic[i] << endl; } 17 | } -------------------------------------------------------------------------------- /Medium/folding-a-note.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | p = [list(input()) for _ in range(n)] 3 | 4 | while len(p[0]) > 1: 5 | tmp = [] 6 | for c in p: 7 | tmp.append([c[~i][::-1]+c[i] for i in range(len(c)//2)]) 8 | p = list(zip(*tmp))[::-1] 9 | print(p[0][0]) 10 | -------------------------------------------------------------------------------- /Medium/folding-paper.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | main() { 8 | map< char, int > x { {'R', 1}, {'L', 1}, {'U', 1}, {'D', 1} }; 9 | map< char, string > y { {'R', "LUD"}, {'L', "RUD"}, {'U', "DLR"}, {'D', "ULR"} }; 10 | string order, side; getline(cin, order); getline(cin, side); 11 | for ( auto c : order ) { x[ y[c][0] ] += x[c]; x[ y[c][1] ] *= 2; x[ y[c][2] ] *= 2; x[c] = 1; } 12 | cout << x[side[0]] << endl; 13 | } -------------------------------------------------------------------------------- /Medium/game-of-life.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | char t[100+2][100+2]; 4 | 5 | main() { 6 | int width,height; 7 | scanf("%d%d\n", &width, &height); 8 | 9 | for (int l = 1; l <= height; l++) { 10 | for (int c = 1; c <= width ; c++) { 11 | t[l][c] = getchar() - '0'; 12 | } 13 | getchar(); 14 | } 15 | for (int l = 1; l <= height; l++) { 16 | for (int c = 1 ; c <= width ; c++) { 17 | int count = t[l-1][c-1] + t[l-1][c] + t[l-1][c+1] 18 | + t[l ][c-1] + t[l ][c+1] 19 | + t[l+1][c-1] + t[l+1][c] + t[l+1][c+1]; 20 | int x; 21 | if (count == 2) x = t[l][c]; 22 | else if (count == 3) x = 1 ; 23 | else x = 0; 24 | putchar('0' + x); 25 | } 26 | putchar('\n'); 27 | } 28 | } -------------------------------------------------------------------------------- /Medium/goro-want-chocolate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int res[150][150] = {0}; 6 | 7 | int computeMin (int h, int w) { 8 | int v_min = 150; int h_min = 150; 9 | if ( h == w ) return 1; 10 | if ( res[h][w] ) return res[h][w]; 11 | 12 | for ( int i = 1; i<= h/2; i++ ) { 13 | int tmp = computeMin(i, w) + computeMin(h-i, w); 14 | h_min = (tmp < h_min) ? tmp : h_min; 15 | } 16 | 17 | for ( int i = 1; i <= w/2; i++ ) { 18 | int tmp = computeMin(h, i) + computeMin(h, w-i); 19 | v_min = (tmp < v_min) ? tmp : v_min; 20 | } 21 | 22 | res[h][w] = (h_min < v_min) ? h_min : v_min; 23 | res[w][h] = res[h][w]; 24 | return res[h][w]; 25 | } 26 | 27 | main() { 28 | int h, w; 29 | scanf("%d%d", &h, &w); 30 | printf("%d\n", computeMin(h, w) ); 31 | } -------------------------------------------------------------------------------- /Medium/gravity-tumbler.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import math 3 | 4 | W, H = [int(i) for i in input().split()] 5 | C = int(input()) 6 | out = [] 7 | 8 | for i in range(H): out.append(input()) 9 | for j in range(C): 10 | for i in range(len(out)): out[i] = sorted(out[i], reverse=True) 11 | out = list(zip(*out)) 12 | 13 | for r in out: print(''.join(r)) 14 | -------------------------------------------------------------------------------- /Medium/gravity.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int a[100]; 4 | 5 | main() { 6 | int w, h; scanf("%d%d", &w, &h); 7 | 8 | for (int i = 0; i < h; i++) { 9 | char line[257]; scanf("%s", line); 10 | for (int j = 0; j < w; j++) { a[j] += (line[j]=='#'); } 11 | } 12 | for (int i = h; i > 0; i--) { 13 | for (int j = 0; j < w; j++) { printf("%c", a[j] < i ? '.':'#'); } 14 | printf("\n"); 15 | } 16 | } -------------------------------------------------------------------------------- /Medium/green-valleys.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | typedef struct _Pt { int val, vis; } Pt; 7 | 8 | int H, N, h; 9 | Pt grid[21][21]; 10 | 11 | void check(int i, int j, pair& cur) { 12 | if ( i < 0 || i > N-1 || j < 0 || j > N-1 ) { return; } 13 | if ( grid[i][j].vis == 0 ) { 14 | grid[i][j].vis = 1; 15 | if ( grid[i][j].val <= H ) { 16 | cur.first++; 17 | cur.second = min(cur.second, grid[i][j].val); 18 | check(i+1, j , cur); 19 | check(i-1, j , cur); 20 | check(i , j+1, cur); 21 | check(i , j-1, cur); 22 | } 23 | } 24 | } 25 | 26 | int main() { 27 | cin >> H >> N; cin.ignore(); 28 | pair res = make_pair(0, 0); 29 | 30 | for (int i = 0; i < N; i++) 31 | for (int j = 0; j < N && cin >> h; j++) { grid[i][j] = { h , 0 }; } 32 | 33 | for (int i = 0; i < N; i++) 34 | for (int j = 0; j < N; j++) { 35 | if ( grid[i][j].val <= H && grid[i][j].vis == 0 ) { 36 | pair cur = make_pair(0, H); 37 | check(i, j, cur); 38 | if ( cur.first > res.first ) { res = cur; } 39 | else if ( cur.first == res.first ) { if(cur.second < res.second) { res.second = cur.second; } } 40 | } 41 | } 42 | cout << res.second << endl; 43 | } -------------------------------------------------------------------------------- /Medium/guessing-n-cheating.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define MIN(a,b) (((a)<(b))?(a):(b)) 5 | #define MAX(a,b) (((a)<(b))?(b):(a)) 6 | 7 | main() { 8 | int R, guess, answer, min = 1, max = 100, cheating = 0; 9 | scanf("%d", &R); fgetc(stdin); 10 | 11 | for (int i = 0; i < R; i++) { 12 | char line[256]; fgets(line, 256, stdin); 13 | char *p = strtok(line, " "); 14 | guess = atoi(p); 15 | p = strtok(NULL, ""); 16 | 17 | if ( *(p+4) == 'h' ) { max = MIN(max, guess - 1); } 18 | else if ( *(p+4) == 'l' ) { min = MAX(min, guess + 1); } 19 | 20 | if ( (max < min) || ((*(p+4) == 't') && !(min <= guess && guess <= max)) ) { 21 | printf("Alice cheated in round %d\n", i+1); 22 | cheating = 1; 23 | break; 24 | } 25 | } 26 | if(cheating == 0) printf("No evidence of cheating"); 27 | } -------------------------------------------------------------------------------- /Medium/hacking-at-robbercity.js: -------------------------------------------------------------------------------- 1 | // Solution from DPAmar 2 | 3 | xor = (a,b)=> 4 | { 5 | var res = ''; 6 | for(var i=0; iString.fromCharCode(parseInt(x,16)))) -------------------------------------------------------------------------------- /Medium/halting-sequences.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct T : std::pair { }; 4 | std::istream& operator>>(std::istream& is, T& in) { return is >> in.first >> in.second; } 5 | 6 | int main() 7 | { 8 | std::cin.ignore(std::numeric_limits::max(), '\n'); 9 | std::vector > test{ std::istream_iterator(std::cin), 10 | std::istream_iterator() }; 11 | 12 | for ( const auto& [a, b]: test ) { 13 | int tmp{ (a + b)/std::__gcd(a, b) }; 14 | std::cout << ( (0 == (tmp & (tmp - 1))) ? "halts" : "loops" ) << '\n'; 15 | } 16 | } -------------------------------------------------------------------------------- /Medium/inversion-count.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Linq; 3 | using System.Collections.Generic; 4 | 5 | class Node { 6 | public long m_val, m_sze; 7 | public Node m_lft, m_rht; 8 | 9 | public Node(long p_val) { 10 | m_val = p_val; 11 | m_sze = 1; 12 | } 13 | 14 | public long addNode(Node p_n) { 15 | ++m_sze; 16 | if (p_n.m_val < m_val) { 17 | if (null == m_lft) { 18 | m_lft = p_n; 19 | return m_sze - 1; 20 | } 21 | return m_lft.addNode(p_n) + 1 + (m_rht?.m_sze ?? 0); 22 | } 23 | if (null == m_rht) { 24 | m_rht = p_n; 25 | return 0; 26 | } 27 | return m_rht.addNode(p_n); 28 | } 29 | } 30 | 31 | class Solution { 32 | static void Main(string[] args) { 33 | long[] nums = Array.ConvertAll(Console.ReadLine().Split(' '), long.Parse); 34 | long res = 0; 35 | Node root = null; 36 | for (int i = 0; i < nums[3]; i++) { 37 | nums[2] = nums[1] * nums[2] % nums[0]; 38 | Node node = new Node(nums[2]); 39 | if (root == null) root = node; 40 | else res += root.addNode(node); 41 | } 42 | 43 | Console.WriteLine(res); 44 | } 45 | } -------------------------------------------------------------------------------- /Medium/ip-mask-calculating.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | unsigned char ip[4], tmp; 5 | scanf("%hhd.%hhd.%hhd.%hhd/%hhd", ip+3, ip+2, ip+1, ip, &tmp); 6 | int mask = (tmp == 32) ? 0 : (unsigned)~0 >> tmp; 7 | *(int *)ip &= ~mask; printf("%d.%d.%d.%d\n", ip[3], ip[2], ip[1], ip[0]); 8 | *(int *)ip |= mask ; printf("%d.%d.%d.%d\n", ip[3], ip[2], ip[1], ip[0]); 9 | } -------------------------------------------------------------------------------- /Medium/jumping-frogs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Frog { 4 | int x, y, k; 5 | friend auto& operator>>(std::istream& is, Frog& f) { return is >> f.x >> f.y >> f.k; } 6 | }; 7 | 8 | int main() { 9 | std::istream_iterator is(std::cin), eos; 10 | std::vector f(is, eos); 11 | 12 | bool ret{ true }; 13 | for (int i = 0; i < std::size(f); ++i) { 14 | int j{ (i + 1) % 3 }; 15 | ret &= (abs(f[j].x - f[i].x) % std::__gcd(f[i].k, f[j].k) == 0); 16 | ret &= (abs(f[j].y - f[i].y) % std::__gcd(f[i].k, f[j].k) == 0); 17 | } 18 | std::cout << ( ret ? "Possible\n" : "Impossible\n" ); 19 | } -------------------------------------------------------------------------------- /Medium/kaprekars-routine.js: -------------------------------------------------------------------------------- 1 | let num = (n1 = readline()); 2 | let res = []; 3 | 4 | do { 5 | res.push(num); 6 | num = ( parseInt(num.split('').sort((a,b) => b-a).join('')) - 7 | parseInt(num.split('').sort((a,b) => a-b).join(''))) 8 | .toString().padStart(n1.length, 0); 9 | } while( res.indexOf(num) < 0 ); 10 | 11 | console.log(res.splice(res.indexOf(num)).join(' ')); -------------------------------------------------------------------------------- /Medium/langtons-ant.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct _card { int x, y; } card; 6 | 7 | main() { 8 | int W, H, x, y, T; char d[2], C[31][31]; scanf("%d%d%d%d%s%d", &W, &H, &x, &y, &d, &T); 9 | int dir_i; card dirs[4] = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}}; 10 | switch(*d) { 11 | case 'N': dir_i = 0; break; 12 | case 'E': dir_i = 1; break; 13 | case 'S': dir_i = 2; break; 14 | case 'W': dir_i = 3; break; 15 | } 16 | 17 | for (int i = 0; i < H; i++) { scanf("%s", C[i]); } 18 | for (int i = 0; i < T; i++) { 19 | dir_i = (dir_i + 4 + (C[y][x] == '#' ? 1 : -1)) % 4; 20 | C[y][x] = (C[y][x] == '#' ? '.' : '#'); 21 | x += dirs[dir_i].x; y += dirs[dir_i].y; 22 | } 23 | for (int i = 0; i < H; i++) { printf("%s\n", C[i]); } 24 | } -------------------------------------------------------------------------------- /Medium/length-of-syracuse-conjecture-sequence.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | uint32_t* v; 4 | 5 | inline uint32_t cycleLength(const uint32_t& i) { 6 | if ( v[i] ) return( v[i] ); 7 | v[i]= 1 + cycleLength( (i&1) ? (3*i+1) : i/2 ); 8 | return( v[i] ); 9 | } 10 | 11 | struct Range { 12 | uint32_t A, B; 13 | friend std::istream& operator>>(std::istream& is, Range& r) { return is >> r.A >> r.B; } 14 | }; 15 | 16 | int main() 17 | { 18 | std::cin.ignore(std::numeric_limits::max(), '\n'); 19 | std::istream_iterator it(std::cin), eos; 20 | std::vector ranges(it, eos); 21 | 22 | 23 | v = (uint32_t*)malloc(1570824737*sizeof(uint32_t)); 24 | for(uint32_t i=0;i<30;++i)v[1UL< longest ) { longest = cur; best = i; } 30 | 31 | std::cout << best << " " << longest << "\n"; 32 | } 33 | } -------------------------------------------------------------------------------- /Medium/locked-in-gear.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Gear { 4 | int x, y, r, dir{0}; 5 | friend std::istream& operator>>(std::istream& o, Gear& g) { return o >> g.x >> g.y >> g.r; } 6 | friend std::ostream& operator<<(std::ostream& o, Gear& g) { 7 | static const std::map outputs { {-1,"CCW"}, {0,"NOT MOVING"}, {1,"CW"} }; 8 | return o << outputs.at(g.dir) << "\n"; 9 | } 10 | 11 | bool contact(const Gear& g) const { 12 | return (pow(r + g.r, 2) == pow(x-g.x, 2) + pow(y-g.y, 2)) && ( x != g.x || y != g.y ); 13 | } 14 | }; 15 | 16 | int main() 17 | { 18 | int N; 19 | std::cin >> N; 20 | std::vector gears(N); 21 | for ( auto& gear : gears ) std::cin >> gear; 22 | 23 | std::queue q; 24 | gears.front().dir = 1; 25 | q.push(gears.front()); 26 | 27 | while ( !std::empty(q) ) { 28 | auto cur = q.front(); 29 | q.pop(); 30 | 31 | std::for_each( std::begin(gears), std::end(gears), [&cur, &q](auto& g2){ 32 | if ( cur.contact(g2) ) { 33 | if ( g2.dir == cur.dir ) { std::cout << "NOT MOVING\n"; exit(0); } 34 | else if ( !g2.dir ) { 35 | g2.dir = -cur.dir; 36 | q.push(g2); 37 | } 38 | } 39 | }); 40 | } 41 | 42 | std::cout << gears.back(); 43 | } -------------------------------------------------------------------------------- /Medium/magic-square.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | #define N 1000 6 | int n, c[N][N], res[N], used[N]; 7 | 8 | int main() { 9 | cin >> n; cin.ignore(); 10 | for (int i = 0; i < n; i++) 11 | for (int j = 0; j < n && cin >> c[i][j]; j++) { 12 | if(++used[c[i][j]] > 1 || c[i][j] < 1 || c[i][j] > n*n ) { cout << "MUGGLE" << endl; exit(1); } 13 | res[i ] += c[i][j]; 14 | res[n+j] += c[i][j]; 15 | if (i == j ) res[2*n ]+= c[i][j]; 16 | if (i == (n-1-j)) res[2*n+1]+= c[i][j]; 17 | } 18 | 19 | for (int i = 0; i < 2*n+2; i++) if (res[i] != res[0]) { cout << "MUGGLE" << endl; exit(1); } 20 | cout << "MAGIC" << endl; 21 | } -------------------------------------------------------------------------------- /Medium/mars-lander-ep2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int nbPts ; /*!< Number of landing points */ 6 | int x , y ; /*!< Position components */ 7 | int X , Y ; /*!< Landing coordinates */ 8 | int vx, vy; /*!< Speed components */ 9 | int fuel ; /*!< Remaining fuel level */ 10 | int power ; /*!< Power of the rockets */ 11 | int rotate; /*!< Rotation angle of Mars Lander */ 12 | 13 | // -- Compute the landing position -- // 14 | int l_lastX, l_lastY; 15 | std::cin >> nbPts; 16 | while ( nbPts-- ) 17 | { 18 | std::cin >> x >> y; 19 | 20 | if ( y == l_lastY ) 21 | { 22 | X = ( l_lastX + x )/2; 23 | Y = l_lastY; 24 | } 25 | l_lastX = x; 26 | l_lastY = y; 27 | } 28 | 29 | // -- Play the game -- // 30 | while(1) 31 | { 32 | std::cin >> x >> y >> vx >> vy >> fuel >> rotate >> power; 33 | 34 | rotate = ( (y - Y) > 100 ) ? ( ((x - X) / 100) + vx * 0.64 ) : 0; 35 | power = ( (vy < -20) || (vx*vx > 1600) ) ? 4 : 2; 36 | 37 | std::cout << rotate << " " << power << std::endl; 38 | } 39 | } -------------------------------------------------------------------------------- /Medium/maximum-sub-sequence.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() { 4 | int N, c[1500]; scanf("%d", &N); 5 | for (int i = 0; i < N; i++) { scanf("%d", &c[i]); } 6 | 7 | int idx = -1, sz = 0, st = 1e9; 8 | for (int i = 0; i < N-1; i++) { 9 | int l_idx = i, l_sz = 0, search = c[i]+1, l_st = c[i]; 10 | for (int j = i+1; j < N; j++) if ( c[j] == search ) { search++; l_sz++; } 11 | if ( l_sz > sz || (l_sz == sz && l_st < st) ) {sz = l_sz; idx = l_idx; st = l_st; } 12 | } 13 | for(int i = 0; i < sz; i++) { printf("%d ", c[idx]+i); } 14 | printf("%d", c[idx]+sz); 15 | } -------------------------------------------------------------------------------- /Medium/maze.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | char a[21][22]; 5 | int X, Y, W, H, nRes = 0; 6 | 7 | typedef struct { int x,y; } pt; 8 | pt pRes[100]; 9 | 10 | void check(int x, int y) { 11 | if ( a[y][x] == '.' ) { 12 | a[y][x] = 'X'; 13 | if (x==0 || y==0 || x==W-1 || y==H-1) { pRes[nRes].x=x; pRes[nRes++].y=y; return; } 14 | if ( y+1 < H) check(x , y+1); 15 | if ( y-1 >= 0) check(x , y-1); 16 | if ( x+1 < W) check(x+1 , y ); 17 | if ( x-1 >= 0) check(x-1 , y ); 18 | } 19 | } 20 | 21 | int cmp( const pt * a, const pt *b) { 22 | if (a->x != b->x) return a->x - b->x; 23 | return a->y - b->y; 24 | } 25 | 26 | main() { 27 | scanf("%d%d%d%d", &W, &H, &X, &Y); 28 | for (int y = 0; y < H; y++) { scanf("%s",a+y); } 29 | check(X,Y); 30 | qsort(pRes, nRes, sizeof(pt), cmp); 31 | printf("%d\n", nRes); 32 | for (int i= 0; i < nRes; i++) { printf("%d %d\n", pRes[i].x,pRes[i].y); } 33 | } -------------------------------------------------------------------------------- /Medium/monthly-system.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | char sub[4], *months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", 5 | "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; 6 | 7 | long ctoLong(char *c) { 8 | long l_conv = 0; 9 | for(int i = strlen(c)/3 -1; i >= 0; i--) { 10 | memmove(sub, c, 3); c += 3; 11 | for(int j = 0; j < 12; j++) { if(!strcmp(sub, months[j])){ l_conv += pow(12,i)*j; break; } } 12 | } 13 | return l_conv; 14 | } 15 | 16 | void ltoChar(long l) { 17 | int ind = 0, r[100] = {0}; 18 | while (l > 0) { r[ind++] = (l % 12); l /= 12; } 19 | 20 | for(int i = ind-1; i >=0; i--) { printf("%s", months[r[i]]); } 21 | } 22 | 23 | main() { 24 | int N; scanf("%d", &N); fgetc(stdin); 25 | long conv = 0; 26 | char M[65]; 27 | for (int i = 0; i < N && fgets(M, 65, stdin); i++) { conv += ctoLong(M); } 28 | ltoChar(conv); 29 | } -------------------------------------------------------------------------------- /Medium/network-cabling.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | double ComputeMedian(vector& p_data) 9 | { 10 | size_t size = p_data.size(); 11 | 12 | if (size == 0) return 0; 13 | else 14 | { 15 | sort(p_data.begin(), p_data.end()); 16 | if (size % 2 == 0) return (p_data[size / 2 - 1] + p_data[size / 2]) / 2; 17 | else return p_data[size / 2]; 18 | } 19 | } 20 | 21 | int main() 22 | { 23 | long x_min(2e30), x_max(-2e30); 24 | long y_median; 25 | int N; 26 | long l_result(0); 27 | cin >> N; cin.ignore(); 28 | vector ordinates(N, 0); 29 | 30 | for (auto i = 0; i < N; i++) 31 | { 32 | long X; 33 | cin >> X >> ordinates[i]; cin.ignore(); 34 | 35 | x_min = X < x_min ? X : x_min; 36 | x_max = X > x_max ? X : x_max; 37 | } 38 | 39 | y_median = ComputeMedian(ordinates); 40 | 41 | l_result += x_max - x_min; 42 | for( auto it = ordinates.begin(); it != ordinates.end(); ++it) 43 | { 44 | l_result += abs(*it - y_median); 45 | } 46 | 47 | cout << l_result << endl; 48 | } -------------------------------------------------------------------------------- /Medium/number-of-letters-in-a-number---binary.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void next ( long long& x ) { 5 | long long tmp = x; x = 0; 6 | while (tmp > 0) { x += 4 - tmp % 2; tmp /= 2; } 7 | } 8 | 9 | main() { 10 | long long start, checker, n; cin >> start >> n; cin.ignore(); 11 | while ( n-- && (checker != start) ) { checker = start; next(start); } 12 | cout << start << endl; 13 | } -------------------------------------------------------------------------------- /Medium/number-of-paths-between-2-points.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define _IT(a,b) for (int i = 1; i <= M; i++) { for (int j = 1; j <= N; j++) a; b; } 3 | 4 | int M, N, r = 0, s[101][101]; 5 | 6 | void paths(int p_i, int p_j ) { 7 | if ( p_i== M && p_j == N ) { r++; return; } 8 | if ( p_i < M && s[p_i+1][p_j ] == 0) { paths(p_i+1, p_j ); } 9 | if ( p_j < N && s[p_i ][p_j+1] == 0) { paths(p_i , p_j+1); } 10 | } 11 | 12 | main() { 13 | scanf("%d%d", &M, &N); fgetc(stdin); 14 | _IT(s[i][j] = fgetc(stdin) - '0', fgetc(stdin)); 15 | paths(1,1); 16 | printf("%d\n", r); 17 | } -------------------------------------------------------------------------------- /Medium/oneway-city.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | m = int(input())-1 4 | n = int(input())-1 5 | 6 | print(str(math.comb(m+n,n))[:1000]) -------------------------------------------------------------------------------- /Medium/othello.js: -------------------------------------------------------------------------------- 1 | let grid = [...new Array(8)].map(() => readline().split('')); 2 | const [c, m] = readline().split(' '); 3 | 4 | const getIdx = (char) => [char[1] - 1, char.charCodeAt(0) - 97]; 5 | const [x, y] = getIdx(m); 6 | 7 | const mirror = (p) => { 8 | let m = p.join('').match(/BW+(?=b)|bW+(?=B)|WB+(?=w)|wB+(?=W)/g); 9 | return m ? m.reduce((s, p) => s + p.length - 1, 0) : 0; 10 | }; 11 | 12 | const checkDirs = (x, y) => 13 | mirror(grid[y]) + 14 | mirror(grid.map((a) => a[x])) + 15 | mirror(grid.map((a, i) => a[x - y + i])) + 16 | mirror(grid.map((a, i) => a[x + y - i])); 17 | 18 | const save = grid[x][y]; 19 | grid[x][y] = c.toLowerCase(); 20 | const c = checkDirs(y, x); 21 | grid = grid.join(); 22 | const tks = {W: grid.match(/W/gi).length, B: grid.match(/B/gi).length}; 23 | 24 | tks[c] += c; 25 | tks[c === 'W' ? 'B' : 'W'] -= c; 26 | 27 | console.log( save !== '-' ? 'NOPE' : 28 | c !== 0 ? `${tks.W} ${tks.B}` : 'NULL' ); -------------------------------------------------------------------------------- /Medium/plague-jr.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | def simulate(node, edges, current_min): 4 | queue = deque([(node, 0)]) 5 | visited = {node} 6 | while queue: 7 | node, night = queue.popleft() 8 | if night >= current_min: return current_min 9 | for o in edges[node]: 10 | if o not in visited: 11 | queue.append((o, night + 1)) 12 | visited.add(o) 13 | return night 14 | 15 | def solution(): 16 | num_rods = int(input()) 17 | edges = {} 18 | for _ in range(num_rods): 19 | a, b = map(int, input().split()) 20 | if a not in edges: edges[a] = [] 21 | if b not in edges: edges[b] = [] 22 | edges[a].append(b) 23 | edges[b].append(a) 24 | 25 | current_min = float('inf') 26 | for node in edges: 27 | current_min = simulate(node, edges, current_min) 28 | print(current_min) 29 | 30 | solution() 31 | -------------------------------------------------------------------------------- /Medium/playfair-cipher.py: -------------------------------------------------------------------------------- 1 | keys = [input().split() for _ in range(5)] 2 | dic = dict((keys[y][x], (x, y)) for x in range(5) for y in range(5)) 3 | dm = 1 if input() == 'ENCRYPT' else -1 4 | 5 | for _ in range(int(input())): 6 | msg = [a for a in input().upper() if a in dic] 7 | if len(msg) % 2 == 1: 8 | print('DUD') 9 | else: 10 | for i in range(len(msg)//2): 11 | x1, y1 = dic[msg[2*i ]] 12 | x2, y2 = dic[msg[2*i+1]] 13 | if y1 == y2: 14 | x1, x2 = (x1 + dm) % 5, (x2 + dm) % 5 15 | elif x1 == x2: 16 | y1, y2 = (y1 + dm) % 5, (y2 + dm) % 5 17 | else: 18 | x1, x2 = x2, x1 19 | print(keys[y1][x1], keys[y2][x2], sep='', end='') 20 | print() 21 | -------------------------------------------------------------------------------- /Medium/porcupine-fever.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MIN(a,b)((aa == 0 ) { return; } 9 | int new_sick = MIN( c->h, 2 * c->s ); 10 | c->s = new_sick; 11 | c->h -= new_sick; 12 | c->a = c->s + c->h; 13 | } 14 | 15 | main() { 16 | int N, Y; scanf("%d%d", &N, &Y); 17 | cage c[N]; 18 | for (int i = 0; i < N; i++) { scanf("%d%d%d", &c[i].s, &c[i].h, &c[i].a); } 19 | 20 | for (int i = 0; i < Y; i++) { 21 | int res = 0; 22 | for ( int j = 0; j < N; j++ ) { update(&c[j]); res += c[j].a; } 23 | if ( res == 0 ) { printf("0\n"); break; } 24 | printf("%d\n", res); 25 | } 26 | } -------------------------------------------------------------------------------- /Medium/propositions-in-freges-ideography.py: -------------------------------------------------------------------------------- 1 | from itertools import product 2 | 3 | lines = int(input()) 4 | draw = [] 5 | for _ in range(lines): 6 | draw.append(input()) 7 | 8 | l = len(draw[-1]) 9 | d = set() 10 | 11 | def res(x,y): 12 | while True: 13 | loc=draw[x][y] 14 | if y==l-2: 15 | a=draw[x][y+1] 16 | d.add(a) 17 | return a 18 | if loc=="|": 19 | x+=1 20 | continue 21 | if loc=="'": 22 | y+=1 23 | continue 24 | if loc=="+": 25 | return "not("+res(x,y+1)+")" 26 | if x+1 (count scnd) (count frst)) 10 | [(first scnd)])))) 11 | 12 | (defn queneau-n [n] 13 | (let [q0 (step-queneau (range 1 (inc n)))] 14 | (take n (iterate step-queneau q0)))) 15 | 16 | (defn queneau? [xs] 17 | (= (last xs) (range 1 (inc (count (first xs)))))) 18 | 19 | (defn -main [& args] 20 | (let [qs (queneau-n (read))] 21 | (if (not (queneau? qs)) 22 | (println "IMPOSSIBLE") 23 | (->> (map (partial clojure.string/join ",") qs) 24 | (mapv println))))) -------------------------------------------------------------------------------- /Medium/remaining-card.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int N; std::cin >> N; 5 | std::cout << std::fixed << std::setprecision(0) << (2 * N - pow(2,ceil(log(N)/log(2)))) << "\n"; 6 | } -------------------------------------------------------------------------------- /Medium/reverse-polish-notation.py: -------------------------------------------------------------------------------- 1 | INS = {'ADD': '+', 'SUB': '-', 'MUL': '*', 'DIV': '//', 'MOD': '%'} 2 | n = int(input()) 3 | s = [] 4 | try: 5 | for i in input().split(): 6 | if i in INS: 7 | a, b = s.pop(), s.pop() 8 | r = eval(b + INS[i] + a) 9 | s.append(str(r)) 10 | elif i == 'POP': 11 | s.pop() 12 | elif i == 'DUP': 13 | s.append(s[-1]) 14 | elif i == 'SWP': 15 | s[-1], s[-2] = s[-2], s[-1] 16 | elif i == 'ROL': 17 | s.pop() 18 | s[-3], s[-2], s[-1] = s[-2], s[-1], s[-3] 19 | else: 20 | s.append(i) 21 | except: 22 | s.append('ERROR') 23 | finally: 24 | print(' '.join(s)) 25 | -------------------------------------------------------------------------------- /Medium/reversed-look-and-say.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | string forward(const string& s) 9 | { 10 | ostringstream r; 11 | 12 | for (size_t i = 0; i != s.length();) 13 | { 14 | auto i2 = s.find_first_not_of(s[i], i + 1); 15 | 16 | if ( i2 == string::npos ) { i2 = s.length(); } 17 | 18 | r << i2 - i << s[i]; 19 | i = i2; 20 | } 21 | 22 | return r.str(); 23 | } 24 | 25 | bool backward(string& s) 26 | { 27 | string s2; 28 | 29 | auto i1 = s.begin(); 30 | auto i2 = i1 + 1; 31 | 32 | while ( i1 != s.end() && i2 != s.end() ) 33 | { 34 | for(int i = 0; i < *i1-'0'; i++) 35 | { 36 | s2 += *i2; 37 | } 38 | i1 += 2; 39 | i2 = i1 + 1; 40 | } 41 | 42 | if ( s.compare(forward(s2)) != 0 ) { return true; } 43 | else if ( ( s2.size() % 2 == 1 ) || ( s2.compare(s) == 0 ) ) {s = s2;return true; } 44 | 45 | s = s2; 46 | return false; 47 | } 48 | 49 | int main() 50 | { 51 | string s; 52 | getline(cin, s); 53 | 54 | bool stop = false; 55 | while ( !stop ) 56 | { 57 | stop = backward(s); 58 | } 59 | 60 | cout << s << endl; 61 | } -------------------------------------------------------------------------------- /Medium/robbery-optimisation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define MAX(a,b) (((a) > (b))?(a):(b)) 4 | int N; 5 | long long h [101], res[101]; 6 | 7 | long long a( int i ) { 8 | if ( i >= N ) { return 0; } 9 | if ( res[i] == 0 ) { long long r1 = h[i] + a(i+2), r2 = a(i+1); res[i] = MAX(r1,r2); } 10 | return res[i]; 11 | } 12 | 13 | main() { 14 | scanf("%d", &N); 15 | for (int i = 0; i < N ; i++) { scanf("%lld", &h[i]); fprintf(stderr, "%lld ", h[i]); } 16 | printf("%lld\n", a(0) ); 17 | } -------------------------------------------------------------------------------- /Medium/rod-cutting-problem.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int getMaxValue(int p_length, const std::map& p_vals ) { 6 | std::vector sums(p_length+1, 0); 7 | 8 | for ( const auto& [cutL, cutV] : p_vals ) 9 | for ( int curL = 1; curL <= p_length; curL++ ) 10 | if ( int resL{curL - cutL}; resL >= 0 ) 11 | sums[curL] = std::max( sums[curL], sums[resL] + cutV); 12 | return sums[p_length]; 13 | } 14 | 15 | int main() { 16 | int L, N, curL; 17 | std::map vals; 18 | std::cin >> L >> N; 19 | 20 | for ( int i = 0; i < N; ++i ) 21 | std::cin >> curL >> vals[curL]; 22 | 23 | std::cout << getMaxValue(L, vals) << std::endl; 24 | } -------------------------------------------------------------------------------- /Medium/sandpile-addition.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define CELLS_IF for (int i = 1; i <= n; i++)for (int j = 1; j <= n; j++) 5 | #define CELLS_IT(a,b) for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) a; b; } 6 | 7 | main() { 8 | int n, s[12][12], end; 9 | scanf("%d", &n); fgetc(stdin); 10 | 11 | CELLS_IT(s[i][j] = fgetc(stdin) - '0', fgetc(stdin)); 12 | CELLS_IT(s[i][j] += fgetc(stdin) - '0', fgetc(stdin)); 13 | 14 | do { 15 | end = 1; 16 | CELLS_IF 17 | if ( s[i][j] > 3 ) { s[i][j]-= 4; s[i-1][j]++; s[i+1][j]++;s[i][j-1]++;s[i][j+1]++; end = 0; } 18 | } while (end == 0); 19 | 20 | for (int i = 1; i <= n; i++) { 21 | for (int j = 1; j <= n; j++) printf("%d", s[i][j]); 22 | printf("\n"); 23 | } 24 | } -------------------------------------------------------------------------------- /Medium/snake-encoding.js: -------------------------------------------------------------------------------- 1 | var N = parseInt(readline()); 2 | var X = parseInt(readline()); 3 | 4 | var arr = []; 5 | var idx = []; 6 | var m = []; 7 | 8 | for ( var i = 0; i < N; i++ ) { arr[i]= readline(); idx[i]= []; } 9 | 10 | for ( var i = 0; i < N; i++ ) { 11 | for ( var j = 0; j < N; j++ ) { 12 | var index = ((j+(j+1)%2)*N + ((j%2==0)? -1 : 1)*i+ (j%2)); 13 | idx[i][j] = index; 14 | m[index] = arr[i][j]; 15 | } 16 | } 17 | 18 | for ( var i = 0; i < N; i++ ) { 19 | var res=''; 20 | for ( var j = 0; j < N; j++ ) { 21 | var index = idx[i][j] -X; 22 | index = index % (N*N); 23 | if( index <= 0 ) index+= N*N 24 | res += m[index]; 25 | } 26 | print(res); 27 | } -------------------------------------------------------------------------------- /Medium/stock-exchange-losses.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int n, l_result(0), next_local_min_index(0); 11 | 12 | cin >> n; cin.ignore(); 13 | vector values(n,0); 14 | for (auto i = 0; i < n; i++) { cin >> values[i]; cin.ignore(); } 15 | 16 | vector::iterator result = values.begin(); 17 | for (auto it = values.begin(); it < values.end(); ++it ) 18 | { 19 | if( next_local_min_index <= distance(begin(values), it) ) 20 | { 21 | result = min_element(it, end(values)); 22 | next_local_min_index = distance(begin(values), result); 23 | } 24 | 25 | int return_val = *result - *it; 26 | 27 | if( *it > *result && abs(return_val) > abs(l_result) ) l_result = return_val; 28 | } 29 | 30 | cout << l_result << endl; 31 | } -------------------------------------------------------------------------------- /Medium/sum-of-divisors.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | main() { 4 | int n; long res = 0; scanf("%d", &n); 5 | for (int i = 1; i <= n; i++) { res+=(long)n/i*i; } 6 | printf("%ld\n", res); 7 | } -------------------------------------------------------------------------------- /Medium/telephone-numbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | struct Node { 10 | map children; 11 | }; 12 | 13 | Node* head; 14 | int cmpt = 0; 15 | 16 | void addTel(string telephone) 17 | { 18 | auto node = head; 19 | for(auto i = 0; i < telephone.size(); ++i) 20 | { 21 | int number = telephone.at(i) + '0'; 22 | auto it = node->children.find(number); 23 | 24 | if(it == node->children.end()) 25 | { 26 | node->children[number] = new Node{}; 27 | cmpt++; 28 | } 29 | node = node->children[number]; 30 | } 31 | } 32 | 33 | int main() 34 | { 35 | int N; 36 | cin >> N; cin.ignore(); 37 | head = new Node{}; 38 | 39 | for (int i = 0; i < N; i++) 40 | { 41 | string telephone; 42 | cin >> telephone; cin.ignore(); 43 | addTel(telephone); 44 | } 45 | 46 | cout << cmpt << endl; 47 | } -------------------------------------------------------------------------------- /Medium/the-experience-for-creating-puzzles.c: -------------------------------------------------------------------------------- 1 | void main() { 2 | int Level, Xp, N; scanf("%d%d%d", &Level, &Xp, &N); 3 | for (int i = 0; i < N; ++i) { 4 | Xp -= 300; 5 | while (Xp <= 0) { Level++; Xp += (int)(Level * sqrt(Level) * 10); } 6 | } 7 | printf("%d\n%d\n", Level, Xp); 8 | } -------------------------------------------------------------------------------- /Medium/the-fastest.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | main() { 5 | int N; scanf("%d", &N); 6 | char t[10], res[10] = "99"; 7 | for (int i = 0; i < N && scanf("%s", t); i++) 8 | if (strcmp(t,res) < 0) strcpy(res, t); 9 | printf("%s\n", res); 10 | } -------------------------------------------------------------------------------- /Medium/the-gift.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | int main() 9 | { 10 | int N, C, total_budget(0); 11 | int average; 12 | int l_return; 13 | cin >> N; cin.ignore(); 14 | cin >> C; cin.ignore(); 15 | vector budgets(N, 0); 16 | 17 | for (int i = 0; i < N; i++) { cin >> budgets[i]; cin.ignore(); total_budget += budgets[i]; } 18 | 19 | sort( budgets.begin(), budgets.end() ); 20 | if ( total_budget < C ) cout << "IMPOSSIBLE" << endl; 21 | else 22 | { 23 | int i = 0; 24 | for ( auto ood : budgets ) 25 | { 26 | average = C / (N - i); 27 | l_return = (ood >= average) ? average : ood; 28 | cout << l_return << endl; 29 | C -= l_return; 30 | i++; 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /Medium/the-grand-festival---i.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int prizes[1000]; 4 | int memory[1000][20]; 5 | int N,R; 6 | 7 | int prize(int index, int days ) { 8 | if ( index == N ) return 0; 9 | if ( memory[index][days] == 0 ) { 10 | int a = ( days == 0 ) ? 0 : prizes[index] + prize( index + 1, days - 1 ); 11 | int b = prize( index + 1, R ); 12 | memory[index][days] = ( a > b ) ? a : b; 13 | } 14 | return memory[index][days]; 15 | } 16 | 17 | main() { 18 | scanf("%d %d", &N , &R); 19 | 20 | for (int i = 0; i < N; i++) { scanf("%d", prizes+i); } 21 | printf("%d", prize( 0 , R )); 22 | } -------------------------------------------------------------------------------- /Medium/the-optimal-urinal-problem.js: -------------------------------------------------------------------------------- 1 | const n = +readline(); 2 | const memo = []; 3 | 4 | const findTotal = (first, last) => { 5 | const dist = last-first; 6 | if (dist <= 3 ) return 0; 7 | const mid = Math.floor((first+last)/2); 8 | memo[dist] = 9 | memo[dist] ? 10 | memo[dist] : findTotal(first, mid) + findTotal(mid, last) + 1; 11 | return memo[dist]; 12 | }; 13 | 14 | const answer = n === 4 || n === 3 ? {max: 2, index: 1}: {max: 1, index: 1}; 15 | let i = 0; 16 | 17 | while (n > 4 && i <= Math.floor(n/2)) { 18 | const total = 19 | (memo[i] ? memo[i] : findTotal(0, i)) + 20 | (memo[n-1-i] ? memo[n-1-i] : findTotal(i, n-1)) + 21 | (i > 1 ? 3 : 2); 22 | if (answer.max < total) { 23 | answer.max = total; 24 | answer.index = i+1; 25 | } 26 | i++; 27 | } 28 | 29 | console.log(answer.max, answer.index); -------------------------------------------------------------------------------- /Medium/the-urinal-problem.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | B = input() 3 | l = max(B.split('!'), key=len) 4 | print(0 if B.index(l) == 0 else (N-1 if B.index(l) + len(l) == N else B.index(l) + len(l)//2)) 5 | -------------------------------------------------------------------------------- /Medium/these-romans-are-crazy!.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | map values { { 'I', 1 }, { 'V', 5 }, { 'X', 10 }, { 'L', 50 }, { 'C', 100 }, { 'D', 500 }, { 'M', 1000 } }; 9 | 10 | int toArabic(const string& p_str) { 11 | int l_return = 0; 12 | for (auto c = p_str.begin(); c < p_str.end()-1; ++c ) 13 | if ( *c == 'I' ) l_return += ( *(c+1) == 'V' || *(c+1) == 'X' ) ? -values[*c] : values[*c]; 14 | else if ( *c == 'X' ) l_return += ( *(c+1) == 'L' || *(c+1) == 'C' ) ? -values[*c] : values[*c]; 15 | else if ( *c == 'C' ) l_return += ( *(c+1) == 'D' || *(c+1) == 'M' ) ? -values[*c] : values[*c]; 16 | else l_return += values[*c]; 17 | l_return += values[*(p_str.end()-1)]; 18 | return l_return; 19 | } 20 | 21 | void toRoman(int p_int) { 22 | int bases[] = {1000,900,500, 400,100, 90, 50, 40, 10, 9, 5, 4, 1 }; 23 | char *symbol[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"}; 24 | int i = 0; 25 | while(p_int) { 26 | while(p_int/bases[i]) { cout<< symbol[i]; p_int -= bases[i]; } 27 | i++; 28 | } 29 | } 30 | 31 | main() { 32 | string a, b; cin >> a >> b; cin.ignore(); 33 | toRoman( toArabic(a) + toArabic(b) ); 34 | } -------------------------------------------------------------------------------- /Medium/tiny-forest.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | struct Pos { 4 | int x, y; 5 | static int w, h; 6 | bool operator<(const Pos& o) const noexcept { return o.y != y ? y < o.y : x < o.x; } 7 | operator bool() const noexcept { return (0 <= x) && (w > x) && (0 <= y) && (h > y); } 8 | }; 9 | 10 | int Pos::w{ 0 }, Pos::h{ 0 }, res{ 0 }; 11 | std::set trees; 12 | enum ACTION{ COUNT = 2, INSERT}; 13 | 14 | int perform( const Pos& p, ACTION act ) { 15 | int res{ 0 }, val{ static_cast(act) }; 16 | for ( int i{ -val }; i <= val; ++i ) 17 | for ( int j{ -val + abs(i) }; j <= val - abs(i); ++j ) 18 | if( Pos nxt{ p.x + j, p.y + i}; nxt ) 19 | if (INSERT == act ) { trees.insert(nxt); } 20 | else if ( 0 == trees.count(nxt) ) { res++; } 21 | return res; 22 | } 23 | 24 | int main() { 25 | std::string input; 26 | std::cin >> Pos::w >> Pos::h; 27 | std::cin.ignore(); 28 | 29 | for ( int y{ 0 }; y < Pos::h && getline(std::cin, input); ++y ) 30 | for( int x{ 0 }; x < Pos::w; ++x ) 31 | if ( 'Y' == input[x] ) perform( {x, y}, INSERT ); 32 | 33 | for ( int y{ 0 }; y < Pos::h; ++y ) 34 | for ( int x{ 0 }; x < Pos::w; ++x ) 35 | res = std::max(res, perform( {x, y}, COUNT )); 36 | 37 | std::cout << std::size(trees) + res; 38 | } -------------------------------------------------------------------------------- /Medium/trits-balanced-ternary-computing.c: -------------------------------------------------------------------------------- 1 | // Inpired from Alain Delpuch answer 2 | #include 3 | 4 | void f(int n, char *t) { 5 | int r = n%3; 6 | n = n/3 + (r==2); 7 | if (n) f (n,t); 8 | putchar(t[r]); 9 | } 10 | 11 | int TriToInt(const char * tri){ 12 | int c, res = 0; 13 | while ( c = *tri++ ) { 14 | switch(c) { 15 | case '1' : res = 3 * res + 1; break; 16 | case '0' : res = 3 * res + 0; break; 17 | case 'T' : res = 3 * res - 1; break; 18 | } 19 | } 20 | return res; 21 | } 22 | 23 | main() { 24 | char l[11], op[6], r[11]; scanf("%s%s%s", l,op,r); 25 | int a = TriToInt(l), b = TriToInt(r); 26 | switch (*op) { 27 | case '<': while (b--) a *= 3; break; 28 | case '>': while (b--) a /= 3; break; 29 | case '*': a *= b; break; 30 | case '+': a += b; break; 31 | case '-': a -= b; break; 32 | } 33 | if (a >= 0) f( +a,"01T"); 34 | else f( -a,"0T1"); 35 | } -------------------------------------------------------------------------------- /Medium/vote-counting.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | int main() { 10 | map votes; 11 | map res = { {1, 0}, {0, 0}, {-1,0} }; 12 | map > tp; 13 | string tmp_name, tmp_vote; 14 | int N, M, tmp_nbVote; cin >> N >> M; cin.ignore(); 15 | 16 | for (int i = 0; i < N && cin >> tmp_name >> tmp_nbVote; i++) { votes[tmp_name] = tmp_nbVote; } 17 | for (int i = 0; i < M && cin >> tmp_name >> tmp_vote; i++) 18 | if ( votes.find(tmp_name) != votes.end() ) { 19 | if ( !tmp_vote.compare("Yes") ) { tp[tmp_name].push_back(1 ); } 20 | else if ( !tmp_vote.compare("No") ) { tp[tmp_name].push_back(0 ); } 21 | else { tp[tmp_name].push_back(-1); } 22 | } 23 | 24 | for(auto& i : tp) 25 | if( i.second.size() <= votes[i.first] ) 26 | for ( auto& j : i.second ) res[j]++; 27 | cout << res[1] << " " << res[0] << endl; 28 | } -------------------------------------------------------------------------------- /Medium/ways-to-make-change.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int waysToChange(int N, std::vector V ) { 4 | std::vector ways(N+1, 0); 5 | ways[0] = 1; 6 | 7 | for ( auto& it : V ) 8 | for ( int i = 1; i <= N; i++ ) 9 | if ( it <= i ) { ways[i] += ways[i-it]; } 10 | 11 | return ways[N]; 12 | } 13 | 14 | int main() { 15 | int N; std::cin >> N; 16 | 17 | std::istream_iterator it(std::cin), eos; 18 | std::vector v (++it, eos); 19 | 20 | std::cout << waysToChange(N, v) << std::endl; 21 | } -------------------------------------------------------------------------------- /codingame_banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MericLuc/CodinGame/81ebea71637fc1338fa993bba256511cd75a8729/codingame_banner.png -------------------------------------------------------------------------------- /link.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MericLuc/CodinGame/81ebea71637fc1338fa993bba256511cd75a8729/link.png --------------------------------------------------------------------------------