Please subscribe to the official Codeforces channel in Telegram via the link https://t.me/codeforces_official. ×

You can use several words in query to find by all of them at the same time. In addition, if you are lucky search understands word forms and some synonyms. It supports search by title and author. Examples:

  • 305 — search for 305, most probably it will find blogs about the Round 305
  • andrew stankevich contests — search for words "andrew", "stankevich" and "contests" at the same time
  • user:mikemirzayanov title:testlib — search containing "testlib" in title by MikeMirzayanov
  • "vk cup" — use quotes to find phrase as is
  • title:educational — search in title

Results

1.

dir

Last visit:  16 years ago
Registered:  16 years ago
2.
By FastestFinger, history, 6 years ago, In English
Editorial — Codeforces Round #648 [problem:1365A] <spoiler summary = "Tutorial"> [tutorial : 1365A] </spoiler> <spoiler summary="Code"> <pre><code> #include <bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define int long long const int N = 51; int n, m; int a[N][N]; int32_t main() { IOS; int t; cin >> t; while(t--) { cin >> n >> m; set< int > r, c; for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { cin >> a[i][j]; if(a[i][j] == 1) r.insert(i), c.insert(j); } } int mn = min(n &mdash; r.size(), m &mdash; c.size()); if(mn % 2) cout << "Ashish" << endl; else cout << "Vivek" << endl; } return 0; } </code></pre> </spoiler> This problem was prepared by [user:Ashishgup,2020-06-07] [problem:1365B] <spoiler summary = "Tutorial"> [tutorial : 1365B] </spoiler> <spoiler summary="Code"> <pre><code> #include <bits/stdc++.h> us...
= 0; k < 4; k++) { ll ni = curr.first + dir[k][0]; ll nj = curr.second + dir [k][1, ') { for (ll k = 0; k < 4; k++) { ll ni = i + dir[k][0]; ll nj = j, ; } ll n, m; char arr[N][N]; ll dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};, ; } return res; } ll n, m; char arr[N][N]; ll dir[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1

Full text and comments »

  • Vote: I like it
  • +626
  • Vote: I do not like it

3.
By -is-this-fft-, history, 5 years ago, In English
[Tutorial] The command line: how to read input from file without #ifdef and much more #### Introduction Instead of algorithms and math, I'll be doing something completely different here. There is something that has bothered me for a long time: people not understanding the tools they use to participate in contests and thus failing to take real advantage of them. And it all goes back to not understanding the command line. Some of you might say, "well surely, the command line is something obsolete and you're only clinging to it because you [insert ridiculous amateur-psychology here]?" No! The command line is not obsolete, and unless competitive programming becomes so mainstream that software vendors start writing professional-grade tools aimed specifically at us, it won't be. [cut] $~$ What is the command line? Any of these: ![ ](/predownloaded/bd/b6/bdb6c157b9b3ce5ae046c9064e469e0081f8c0fe.png) As you can see, it comes in many background colors and fonts, but the basic idea is always the same. It's a box you can type commands in, which it will ...
`dir` (Windows) and press Enter. You should see a list of files and folders located in the folder, Once you have got it open, type `ls` (Linux/Mac) or `dir` (Windows) and press Enter. You should

Full text and comments »

  • Vote: I like it
  • +443
  • Vote: I do not like it

4.
By errorgorn, 4 years ago, In English
[Tutorial] Theoretically Faster HLD and Centroid Decomposition This blog was going to be translation of $[1]$ (which is in Chinese) but I think I ended up deviating too much from the source material that it would not be appropriate to call this a translation. Anyways, I am honestly amazed by how ahead of its time this paper is. In its abstract, it starts by saying that the state of art for tree path queries is $O(n \log n + q \sqrt n \log n)$, which I honestly can't fathom how one would arrive, then proceeds to claim that it has found an $O((n+q) \log n)$ algorithm. All the more, in 2007. While I was in the process of writing this blog, [user:smax,2022-07-18] sniped me and posted $[9]$. However, we will focus on static trees **only**. Thanks to [user:oolimry,2022-07-18], [user:everule,2022-07-18] and [user:timreizin,2022-07-18] for proofreading. Note to reader: I am expecting the reader to be familiar with what a splay tree and HLD is. You do not really need to know why splay trees are $O(\log n)$ amortised but you should know what the z...
val=0,mx=0,lazy=0; node (node *_p){ p=_p; } bool dir(){ return this==p->l, ); } else if (u->dir()==u->p->dir()){ rotate(u->p); rotate(u); } else{ rotate(u, bool dir(){ return this==p->l; }, if (dir){ node *child=u->r; par->l=child; if (child) child->p=par;, u->p=par->p; if (!par->head){ if (par->dir()) par->p->l=u; else par->p->r=u; } swap(u, u->p=par->p; if (par->p){ if (par->dir()) par->p->l=u; else par->p->r=u; }, void rotate(node *u){ node *par=u->p; bool dir=u->dir();

Full text and comments »

  • Vote: I like it
  • +245
  • Vote: I do not like it

5.
By ninja_28, history, 6 years ago, In English
CodeCraft-21 and Codeforces Round #711 (Div. 2) Editorial [problem:1498A] ================== #### [**Video Editorial**](https://www.youtube.com/watch?v=lV5cb8wh3sE) **Author and Problemsetting:** [user:ninja_28,2021-03-29] **Editorialist:** [user:sigma_g,2021-03-29] <spoiler summary="Hint"> Can you think of the simplest properties that relate a number and its sum of digits? </spoiler> <spoiler summary="Hint 2"> Note that if $X$ is a multiple of 3, then **both** $X$ as well as the sum of digits of $X$ are a multiple of 3! Can you put this property to use here? </spoiler> <spoiler summary="Hint 3"> If $X$ is a multiple of 3, then $\texttt{gcd-sum}(X) \ge 3$. Therefore, we are guaranteed that at least every third number will satisfy the constraints required by our problem $(\texttt{gcd-sum}(X) > 1)$. </spoiler> <spoiler summary="Solution"> Therefore, for the input $n$, we can simply check which one of $n$, $n+1$, and $n+2$ has its gcd-sum $> 1$, and print the lowest of them. </spoiler> <spoi...
# backward dir for n in range(1, N + 1): ans = 2, ans %= mod; dp[curr][k][dir] = ans; }, dir) { if (k == 1) { return 1; } if (dp[curr][k][dir] != -1, for k in range(2, K + 1): # forward dir for n in range(N, 0, -1, if (curr < n) ans += solve(curr + 1, k - 1, 1 - dir) - 1;, if (curr > 1) ans += solve(curr - 1, k - 1, 1 - dir) - 1;, if (dir == 1) { if (curr < n) ans += solve(curr + 1, k, dir) - 1;, if (dp[curr][k][dir] != -1) { return dp[curr][k][dir]; }, int solve(int curr, int k, int dir) { if (k == 1) { return 1; }

Full text and comments »

  • Vote: I like it
  • +419
  • Vote: I do not like it

6.
By sum, history, 3 years ago, In English
Editorial for Codeforces Round #919 (Div. 2) ##Information about the round <spoiler summary="Rating predictions (inspired by BucketPotato's editorial)"> | Person | A | B | C | D | E | F1 | F2 | |--------------------------------------------|------|------|------|------|------|------|------| | [user:sum,2024-01-13] | 800 | 1300 | 1500 | 1900 | 2000 | 2200 | 2900 | | [user:oursaco,2024-01-13] | 800 | 1100 | 1300 | 1600 | 1800 | 2100 | 3100 | | [user:omeganot,2024-01-13] | 900 | 1000 | 1400 | 1700 | 1900 | 2200 | 2800 | | [user:sriniv,2024-01-13] | | | | 1900 | 2000 | 1900 | | | [user:apple_method,2024-01-13] | 1000 | 1200 | 1400 | 1900 | 1600 | | | | [user:awesomeguy856,2024-01-13] | 800 | 1100 | 1400 | 1800 | 1900 | 2000 | 2800 | | [user:nonrice,2024-01-13] | 900 | 1000 | 1400 | 1750 | | | | | [user:null_aw...
++){ // Look at cells to the up and left (so dir = 0 and dir = 1) for (int dir = 0;dir, ] = true; for (int dir = 0; dir < 4; dir++) getReach(i + diAdj[dir], j + djAdj[ dir, bool ok = false; for (int dir = 0; dir < 8; dir++) ok |= reachBorder(i + diDiag[ dir, for (int dir = 0; dir < 4; dir++) getReach(i + diAdj[dir], j + djAdj[dir], minVal, for (int dir = 0; dir < 4; dir++){ int ni = i + diAdj[dir], nj = j + djAdj[dir];, for (int dir = 0; dir < 4; dir++){ int ni = i + di[dir], nj = j + dj[dir];

Full text and comments »

  • Vote: I like it
  • +314
  • Vote: I do not like it

7.
By Monogon, history, 6 years ago, In English
[Tutorial] Voronoi Diagram and Delaunay Triangulation in O(n log n) with Fortune's Algorithm What's a Voronoi Diagram? ------------------ Given a set $S$ of $n$ points in the 2D plane, the Voronoi diagram is a partition of the plane into regions. The region associated with a point $p\in S$ contains precisely the points $q$ such that $q$ is closer to $p$ than any other point in $S$. In other words, a point $q$ belongs to the region of its nearest neighbor. <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/54/Euclidean_Voronoi_diagram.svg/1024px-Euclidean_Voronoi_diagram.svg.png" width="300px" height="auto"/> The Voronoi diagram can be represented by the planar graph of boundaries between regions. A vertex in this graph is where three or more segments meet (or a point at infinity), and an edge is a segment connecting two of these vertices. The way the regions were defined, we see that a segment contains the points equidistant to two points in $S$, so it is part of their perpendicular bisector. Similarly, a Voronoi vertex is equidistant to three or more v...
med = (p + q) * 0.5; pt dir = (p - med).rot(); ftype D = (x - p.x) * (x - q.x, ; pt dir = (p - med).rot(); ftype D = (x - p.x) * (x - q.x); return med.y

Full text and comments »

  • Vote: I like it
  • +499
  • Vote: I do not like it

8.
By bicsi, history, 7 years ago, In English
Link Cut Tree implementation Hello! Recently I have been trying to learn link cut trees (and splay trees, for that matter). I have tried to polish an implementation that is short (for our ICPC notebooks), and also easy to use and extend. I might be extending this blog post towards a tutorial on how link cut trees are used and, more so, how this template can be used. The implementation is here: <spoiler summary="Implementation"> ``` struct SplayTree { struct Node { int ch[2] = {0, 0}, p = 0; long long self = 0, path = 0; // Path aggregates long long sub = 0, vir = 0; // Subtree aggregates bool flip = 0; // Lazy tags }; vector<Node> T; SplayTree(int n) : T(n + 1) {} void push(int x) { if (!x || !T[x].flip) return; int l = T[x].ch[0], r = T[x].ch[1]; T[l].flip ^= 1, T[r].flip ^= 1; swap(T[x].ch[0], T[x].ch[1]); T[x].flip = 0; } void pull(int x) { int l = T[x].ch[0], r = T[x].ch[1]; push...
].p = x; pull(x); } void splay(int x) { auto dir = [&](int x) { int p = T[x].p, void splay(int x) { auto dir = [&](int x) { int p = T[x].p; if (!p) return -1

Full text and comments »

  • Vote: I like it
  • +235
  • Vote: I do not like it

9.
By smax, 4 years ago, In English
[Tutorial] Fully Dynamic Trees Supporting Path/Subtree Aggregates and Lazy Path/Subtree Updates Hey everyone! Usually when I post stuff on CF I just drop an external link to my blog, but this time I would like to also paste the same content natively on CF to see if it leads to more engagement. You can read the exact same article on my blog [here](https://mzhang2021.github.io/cp-blog/ds5/). Also, special thanks to [user:alien_lover,2022-06-10] and [user:gabrielwu,2022-06-10] for proofreading. --- ## Motivation We will solve **[this problem](https://dmoj.ca/problem/ds5)**. ## Prologue The original name of this problem is [SONE1](https://darkbzoj.cc/problem/3153), originating from the fiery depths of Chinese OI. Amazingly, the Chinese have figured out how to augment the link/cut tree to solve this problem (ref [1](https://www.cnblogs.com/clrs97/p/4403244.html), [2](https://blog.csdn.net/iamzky/article/details/43494481)). Maintaining subtree aggregates with a LCT isn't difficult, and there's a well-known [Codeforces article](https://codeforces.me/blog/entry/67637) ...
d, int v) { tr[u].ch[d] = v; tr[v].p = u; pull(u); } int dir(int u) { int v, ); while (~dir(u, o) && (o == 0 || tr[tr[u].p].fake)) { int v = tr[u].p, w = tr[v].p, [v].p; attach(w, dir(v, 2), tr[v].ch[dir(u, 2) ^ 1]); if (tr[w].fake, ```c++ int dir(int u, int o) { int v = tr[u].p; return tr[v].ch[o] == u ? o : tr[v].ch[o, ```c++ } else { attach(v, dir(u, 2), 0); } ```, int dir(int u) { int v = tr[u].p; return tr[v].ch[0] == u ? 0 : tr[v].ch[1] == u ? 1 : -1; }, int dir(int u, int o) { int v = tr[u].p; return tr[v].ch[o] == u ? o : tr[v].ch[o+1] == u, void rotate(int u) { int v = tr[u].p, w = tr[v].p, du = dir(u), dv = dir(v); attach(v, du, void rotate(int u, int o) { int v = tr[u].p, w = tr[v].p, du = dir(u, o), dv = dir(v, o, void splay(int u) { push(u); while (~dir(u)) { int v = tr[u].p, w = tr[v].p

Full text and comments »

  • Vote: I like it
  • +259
  • Vote: I do not like it

10.
By FetFot, 18 months ago, In English
Codeforces Round 1025 (Div. 2) Editorial Thank you for your participation! We hope you enjoyed the problems! We would love to hear your feedback! Please share your thoughts in the comments. <br> <spoiler summary="How did you find the contest?"> - Great: - Good: - Average: - Bad: - Trash: </spoiler> <spoiler summary="Which problem was your favorite?"> - A: - B: - C1: - C2: - C3: - D: - E: - F: </spoiler> <spoiler summary="Which problem did you find the least enjoyable?"> - A: - B: - C1: - C2: - C3: - D: - E: - F: </spoiler> <br> [problem:2109A] Idea by [user:MOUFLESS,2025-05-17], prepared by [user:MO...
{ for (int dir = 0; dir < 8; ++dir) { int ni = i + dx[dir]; int nj = j + dy, ) { continue; } for (int dir = 0; dir < 4; ++dir) { int ni = i + dx[dir, ; } for (int dir = 0; dir < 4; ++dir) { int ni = i + dx[dir]; int nj, ] != cost) { continue; } for (int dir = 0; dir < 8; ++dir

Full text and comments »

  • Vote: I like it
  • +251
  • Vote: I do not like it

11.
By installb, history, 14 months ago, In English
Codeforces Round 1048 (Div. 1, Div. 2) Editorial [2139A &mdash; Maple and Multiplication](https://codeforces.me/contest/2139/problem/A) Idea: [user:installb,2025-09-08] Preparation: [user:installb,2025-09-08],[user:2014CAIS01,2025-09-08] <spoiler summary="Solution"> If $a=b$ we need $0$ steps. If $a$ can be divided by $b$, we only need $1$ step, which is to multiply $b$ by $\frac{a}{b}$. Same for the case when $b$ can be divided by $a$. Otherwise, we need at most $2$ steps. As both $a$ and $b$ are positive integers, we can first multiply $a$ by $b$ and then multiply $b$ by the original value of $a$. Both number will be equal to $a\times b$. </spoiler> <spoiler summary="Code (C++)"> ```cpp #include <bits/stdc++.h> using namespace std; typedef long long ll; int solve(){ int a,b; cin >> a >> b; if(a == b) return 0; if(a % b == 0 || b % a == 0) return 1; return 2; } int main(){ ios::sync_with_stdio(false); int TC; cin >> TC; while(TC --){ cout <<...
- p[2]); ans[1] = {1,2,3}; ans[2] = {2,3,4}; point dir = target - p[4]; int, int solve1a(){ point dir = target - p[1]; int split = ceil(len(dir) - 1e-9); int c, int solve1b(){ point dir = target - p[2]; int split = ceil(len(dir) - 1e-9); int c, int solve3a(){ p[3] = point(0.5,sqrt(3.0) / 2); ans[1] = {1,2,3}; point dir = target, int solve3b(){ p[3] = point(0.5,sqrt(3.0) / 2); ans[1] = {1,2,3}; point dir = target, }); if(len(p[w] - target) <= eps_dis) fl = 1; } return 1; } int solve1a(){ point dir

Full text and comments »

  • Vote: I like it
  • +235
  • Vote: I do not like it

12.
By cry, 3 years ago, In English
CodeTON Round 8 Editorial Thank you for participating! We put a lot of effort into this contest. Special thanks to [user:TheScrasse,2024-03-10] for contributing to these problems. <spoiler summary="Rating Predictions"> | Person | A | B | C1 | C2 | D | E | F | G | H | |--------------------------------------------|------|------|------|------|------|------|------|------|------| | [user:oursaco,2024-03-30] | 800 | 1200 | 1500 | 1800 | 2200 | 2400 | 2800 | 2700 | 3400 | | [user:priyanshu.p,2024-03-30] | 800 | 1200 | 1300 | 1600 | 2200 | | | | | | [user:thescrasse,2024-03-30] | 800 | 1200 | 1400 | 1700 | 2100 | 2300 | 2900 | 2900 | 3500 | | [user:cry,2024-03-30] | 800 | 1000 | 1300 | 1700 | 2100 | 2200 | 2800 | 2900 | 3500 | | [user:buffering,2024-03-30] | 800 | 1000 | 1500 | 1900 | 2100 | 2200 | 2700 | 2800 | 3500 | | [user:jaggubandar,2024...
int in[500005], out[500005]; int dir[500005];

Full text and comments »

  • Vote: I like it
  • +143
  • Vote: I do not like it

13.
By eren__, 18 months ago, In English
Codeforces Round 1024 (Div. 1, Div. 2) Editorial Thank you for participating! We hope you enjoyed the problems and, most importantly, had fun! <br> ##[problem:2102A] <spoiler summary="Hints"> <spoiler summary="Hint 1">If you have the first $p$ elements, what happens to the rest?</spoiler> <spoiler summary="Hint 2">What happens if $n\%p\neq0$?</spoiler> <spoiler summary="Hint 3">How can the fact that we can also use negative numbers be useful?</spoiler> </spoiler> <spoiler summary="Solution"> The first thing to realize is that if the first $p$ elements of the array are determined, the rest will be unique ($a_i = a_{i-p}$ to hold the sum). If $p$ divides $n$, there will be $\frac{n}{p}$ blocks, each summing to $q$, so their total sum which is $q\cdot \frac{n}{p}$ should be equal to $m$. If not, the incomplete block that is created at the end can be used to cover any difference in sum, so it's always possible! </spoiler> <spoiler summary="Code (Python 3)">``` t = int(input()) for _ in range(t):...
dir = [(0, 1), (1, 0), (0, -1), (-1, 0)], step += d % 2; dx, dy = dir[d]

Full text and comments »

  • Vote: I like it
  • +185
  • Vote: I do not like it

14.
By errorgorn, 4 years ago, In English
Catalan Numbers and Generating Uniform Balanced Bracket Sequences Hi everyone! Today [user:nor,2022-05-27] sir and I would like to talk about generating uniform bracket sequences. Over the past few years when preparing test cases, I have had to generate a uniform bracket sequence a few times. Unfortunately I could not figure out how, so I would like to write a blog about this now. Hopefully this blog would be useful to future problem setters :) Scroll down to the end of the blog to copy our generators. First, let's define some things. A bracket sequence is a string with $n$ $\texttt{(}$ s and $n$ $\texttt{)}$ s. A **balanced** brackets sequence is a bracket sequence with the additional constraint that it becomes a valid arithmetic expression when we add some $\texttt{1}$ s and $\texttt{+}$ s. Let $p$ be the prefix sum array of a bracket sequence (we assign $1$ to $\texttt{(}$ and $-1$ to $\texttt{)}$ and take the prefix sum). For example, if our bracket sequence is $\texttt{())()((())}$, then $p=[1,0,-1,0,-1,0,1,2,1,0]$. An alternate way to thi...
& [n1, n2, dir] : r) { if (n1 != -1) n1 = p[n1]; if (n2 != -1) n2 = p[n2

Full text and comments »

  • Vote: I like it
  • +205
  • Vote: I do not like it

15.
By peti1234, 5 years ago, In English
Codeforces Round #783 Editorial Hope you enjoyed the problems. <spoiler summary="Direction Change"> [problem:1668A] <spoiler summary="Solution"> The moves are symmetrical, so we can assume that $n≥m$. There is no solution if $m=1$ and $n≥3$, because one can only move up and down, but two consecutive down moves is required to reach $(n, 1)$. Otherwise, there is a solution. One should move downwards at least $n-1$ times, and it is forbidden to do that twice in a row, so another $n-2$ move is necessary ($1$ between each pair). So at least $n-1+n-2=2 \cdot n-3$ moves required. If $n+m$ is even, then one more, because the parity of $a+b$ changes after every move, and the parity is even before the first and after the last move, so the total number of moves should be even. There is a construction for that lower bound: Move alternately down and right. After reaching the $m$-th column, repeat the following sequence of moves: down, left, down, right. With this $4$ move long sequence, one can move down t...
) { if (i < dir[i]) swap(arr[i] , arr[dir[i]]); } for(int i = 1 ; i < need ; i <<= 1, ; a = a * a % mod; b >>= 1;} return tms; } int dir[_] , need , invnd , w[_]; void, int dir[_] , need , invnd , w[_]; void init(int len){ static int L = 1; need = 1; while (need

Full text and comments »

  • Vote: I like it
  • +146
  • Vote: I do not like it

16.
By dmkozyrev, history, 3 years ago, In English
[Tutorial] Quick start in solving problems on GPU + CPU Hello, codeforces! Do you have modern GPU and CPU and want to calculate something with them, but you don't know how to do it? Dont be upset, because you can read this blog and run your first GPU program on your AMD/Intel/NVIDIA GPU. I will describe an installation process and then we will dive into the C++ code. As an example, we will calculate a lot of mazes for [Bug Game](https://codeforces.me/blog/entry/115144) in parallel. For doing this in simple way, we will use library [Boost.Compute](https://www.boost.org/doc/libs/1_80_0/libs/compute/doc/html/index.html), which is a C++ STL-style wrapper over OpenCL library. [cut] ... Installation for MacOS (Apple M1 Pro) ================== As [user:Gosunov,2023-06-10] said, `OpenCL` and `g++` are pre-installed on `MacOS`. Everything that you have to do is install `Boost` with command `brew install boost`. After this you will be able to compile your program with command `g++ -std=c++17 -O3 -I/opt/homebrew/Cellar/boost/1.81.0_1/...
+ 1, dir = +31; while (pos != 618) { ++a.nVis[pos]; unsigned val = a.nVis, ~~~~~ BOOST_COMPUTE_FUNCTION(Field, bugMovingGPU, (Field a), { int pos = 1 * 31 + 1,dir, ~~~~~ __attribute__((noinline)) void bugMovingCPU(Field &a) { int pos = 1 * 31 + 1,dir

Full text and comments »

  • Vote: I like it
  • +118
  • Vote: I do not like it

17.
By EmeraldBlock, history, 3 years ago, In English
IOI 2023 Robot Contest in Z* = 5 [IOI 2023 Robot Contest](https://ioi2023.hu/tasks/#:~:text=robot%20%E2%80%93%20Robot%20Contest) is a great task that reminds me of Turing machines and cellular automata. <spoiler summary="If the task statement is too intimidating..."> Your goal is to program the robot _Pulibot_ to label a shortest path between the northwest and southeast corners of a 2D grid with obstacles, which are guaranteed to be reachable from each other. However, Pulibot is short-sighted and has no memory. Knowing only the colors of the cell it is at and the 4 adjacent cells (including special "colors" for out-of-bounds cells and obstacles), it has to decide what to recolor its current cell and which direction to move in (including not moving, as well as terminating). Pulibot cannot move out-of-bounds or into obstacles. Initially, all empty cells are colored "blank", and Pulibot starts at the northwest corner. After Pulibot terminates, the cells colored "path" must form a shortest path, while th...
if (0 <= h-West && h-West < 4) { int dir = h-West; if (S[dir+1]-West == (dir +2)%4, ]}; } return IMP; } } else if (0 <= h-West && h-West < 4) { int dir = h-West

Full text and comments »

  • Vote: I like it
  • +194
  • Vote: I do not like it

18.
By doreshnikov, history, 5 years ago, In English
Codeforces Round #753 (Div. 3) Editorial ### Short information Sorry for another delayed editorial, I know I promised that it will come out sooner the previous time, but I wasn't feeling well today, so the work was slower than usual. **About problem F:** I am once again sorry for the inconveniences caused by tight ML in this problem. It was not the intended behavior since we relied too much on the main solution and didn't assume most of the solutions using DFS will fail. In this editorial I attach the code of the main solution that we expected from the beginning, it uses ~75MB of memory. I guess, Div. 3 Rounds are not only for participants to learn but also can serve as educational for authors as well. I'll try not to repeat the same mistakes the next time :) Thanks to everyone for participating and hope to see you again! ### The editorial [problem:1607A] Idea: [user:doreshnikov,2021-11-04], [user:MikeMirzayanov,2021-11-04] <spoiler summary="Tutorial"> [tutorial:1607A] </spoiler> <spoiler summar...
>> m; vector dir(n); for (int i = 0; i < n; i++) cin >> dir[i, >> n >> m; vector dir(n); for (int i = 0; i < n; i++) cin, ); if (dir[nr][nc] == 'L') nc--; else

Full text and comments »

  • Vote: I like it
  • +122
  • Vote: I do not like it

19.
By Edvard, history, 11 years ago, translation, In English
Editorial of Educational Codeforces Round 10 ### [problem:652A] The problem was suggested by [user:unprost,2016-03-26]. Let's consider three cases. 1. $h_1+8a \ge h_2$ &mdash; in this case the caterpillar will get the apple on the same day, so the answer is $0$. 2. The first condition is false and $a \le b$ &mdash; in this case the caterpillar will never get the apple, because it can't do that on the first day and after each night it will be lower than one day before. 3. If the first two conditions are false easy to see that the answer equals to $\lceil \frac{h_2-h_1-8a}{12(a-b)} \rceil$. <spoiler summary="C++ solution"> ~~~~~ int h1, h2; int a, b; bool read() { return !!(cin >> h1 >> h2 >> a >> b); } void solve() { if (h1 + 8 * a >= h2) puts("0"); else if (a > b) { int num = h2 - h1 - 8 * a, den = 12 * (a - b); cout << (num + den - 1) / den << endl; } else puts("-1"); } ~~~~~ </spoiler> Also this problem can be so...

Full text and comments »

  • Vote: I like it
  • +43
  • Vote: I do not like it

20.
By Tommyr7, history, 9 years ago, In English
Codeforces Round #462 Editorial Hi, all! This is not [user:Tommyr7,2018-02-14], but the **impostor** behind the round again (guess who I am? :P). The statements are written by me. Thank you, everyone, and hope you've all enjoyed the round! Any feedback on problems and tutorials are welcome — we look forward to doing even better in the future! Here are some of the detailed tutorials! ### Tutorials ### [problem:934A] **Author** [user:quailty,2018-02-14] / **Preparation** [user:quailty,2018-02-14] / **Tutorial** [user:quailty,2018-02-14] <spoiler summary="Tutorial"> [tutorial:934A] </spoiler> <spoiler summary="Solution (quailty)"> ~~~~~ #include<bits/stdc++.h> using namespace std; typedef long long ll; const ll INF=(1LL<<60)-1; ll a[55],b[55]; int main() { int n,m; scanf("%d%d",&n,&m); for(int i=1;i<=n;i++) scanf("%lld",&a[i]); for(int i=1;i<=m;i++) scanf("%lld",&b[i]); ll res=INF; for(int i=1;i<=n;i++) { ll now=-INF; ...
) return vector(); db dt=(c1.r*c1.r-c2.r*c2.r)/d,d1=(d+dt)/2; Point dir=(c2.o-c1, >(); db dt=(c1.r*c1.r-c2.r*c2.r)/d,d1=(d+dt)/2; Point dir =(c2.o-c1.o)/d,pcrs=c1.o

Full text and comments »

  • Vote: I like it
  • +66
  • Vote: I do not like it

21.
By Wild_Hamster, history, 10 years ago, In English
Codeforces Round #355 (Div. 2) Editorial [problem:677A] For each friend we can check, if his height is more than $h$. If it is, then his width is $2$, else $1$. Complexity $O(n)$. <spoiler summary="Code"> ~~~~~ #include <iostream> using namespace std; typedef long long ll; ll i,n,h,ans,x; int main() { cin >> n >> h; ans = n; for (i = 0; i < n; i++) { cin >> x; ans += (x>h); } cout << ans << endl; return 0; } ~~~~~ </spoiler> [problem:677B] The solution, that does same thing, as in the problem statement will fail with TL, because if the height of each piece of potato will be $10^9$ and smashing speed will be $1$, then for each piece we will do $10^9$ operations. With each new piece of potato $a_i$ we will smash the potato till $a[i]$ $MOD$ $k$, so we will waste $a[i]/k$ seconds on it. If we can not put this piece of potato after that, we will waste $1$ more second to smash everything, that inside, else just put this piece. We will get an answe...
1000000007 #define N 2005 using namespace std; typedef unsigned int ll; ll i,j,n,h,x,y,cur_h,k,dir, a[505][505], dp[505][505], d[505][505]; ll dir[4][2] = {{-1,0},{1,0},{0,1},{0,-1}}; vector, ,cur_h,k,m,p,fx,fy; ll a[505][505], dp[505][505], d[505][505]; ll dir[4][2] = {{-1,0},{1,0},{0,1},{0, [505][505], dp[505][505], d[505][505], t[4][2005][2005]; ll dir[4][2] = {{-1,0},{1,0},{0,1},{0,-1, ][505], d[505][505]; ll dir[4][2] = {{-1,0},{1,0},{0,1},{0,-1}}; vector > g[250505

Full text and comments »

  • Vote: I like it
  • +99
  • Vote: I do not like it

22.
By jay_jayjay, history, 3 months ago, In English
Teamscode Spring 2026 Contest Official Editorial Sorry that this is really late.... Thanks for participating in TeamsCode, and I hope you enjoyed the problems! All problems were written and prepared by [user:culver0412,2026-08-13], [user:justin_g_20,2026-08-13], [user:jay_jayjay,2026-08-13], [user:theyashb,2026-08-13], [user:Buzzy2,2026-08-13], Bryan Zhu, [user:alexlikemath007,2026-08-13], [user:n685,2026-08-13], [user:naturalselection,2026-08-13], [user:AksLolCoding,2026-08-13], [user:eysbutno,2026-08-13], [user:pilliamw,2026-08-13], [user:dutin,2026-08-13], [user:willy108,2026-08-13], [user:gg_gong,2026-08-13], and [user:HaccerKat,2026-08-13]. Also thanks to our testers for valuable feedback, and the Teamscode web and logistics teams for making this contest possible! [Novice A/](https://codeforces.me/gym/106507/problem/A)[Advanced A: Digits](https://codeforces.me/gym/106507/problem/A) === [user:justin_g_20,2026-08-13] is still writing the editorial, for now the solution code is below: <spoiler summary="Python Code"...
i = 0; i < k; i++) { auto &[r, c, d] = cows[i]; char dir; std::cin >> r, ++) { auto &[r, c, d] = cows[i]; char dir; std::cin >> r >> c >> dir, int dir = cows[ind][2]; int nr = i + dr[dir]; int nc = j + dc[dir

Full text and comments »

  • Vote: I like it
  • +21
  • Vote: I do not like it

23.
By gepardo, history, 10 years ago, translation, In English
Tutorial of Codeforces Round #379 (Div. 2) Tutorial for the tasks of the contest. If something isn't clear, you can write in comments :) [tutorial:734A] <spoiler summary="Code"> ~~~~~ #include <iostream> #include <string> using namespace std; int main() { int n; cin >> n; string s; cin >> s; int k_a = 0, k_d = 0; for (int i = 0; i < n; i++) if (s[i] == 'A') k_a++; else k_d++; if (k_a > k_d) cout << "Anton" << endl; if (k_a < k_d) cout << "Danik" << endl; if (k_a == k_d) cout << "Friendship" << endl; return 0; } ~~~~~ </spoiler> [tutorial:734B] <spoiler summary="Code"> ~~~~~ #include <iostream> #include <algorithm> using namespace std; int main() { int k2, k3, k5, k6; cin >> k2 >> k3 >> k5 >> k6; int n256 = min(k2, min(k5, k6)); int n32 = min(k3, k2 - n256); cout << 32 * n32 + 256 * n256 << endl; return 0; } ~~~~~ </spoiler> [tutorial:734C] <spoiler summary="Code"> ~~~~~ #include <iostream> using namespace std; const int max_n = 1000000;...
= in_char(); cur.x = in_int(); cur.y = in_int(); int dir = get_direction(cur); if (dir >= 0, = in_int(); cur.y = in_int(); int dir = get_direction(cur); if (dir >= 0) upd_nearest, ; cur.kind = in_char(); cur.x = in_int(); cur.y = in_int(); int dir = get_direction(cur); if

Full text and comments »

  • Vote: I like it
  • +82
  • Vote: I do not like it

24.
By Manoonzzz, 5 months ago, In English
[Tutorial] Hexagonal Grids — a complete guide for Competitive Programming # [Tutorial] Hexagonal Grids — a complete guide for Competitive Programming Sooner or later a problem hands you a **hexagonal grid** instead of the friendly square grid, and the staggered rows make neighbors, distances and BFS feel awkward. This guide builds up the whole toolkit from scratch. The punchline you should keep in mind the entire time is this: **a hex grid is a 3D cube grid seen edge-on.** Once you adopt the right coordinates, every hex algorithm becomes a small variation on something you already know from square grids. **Contents** 1. Geometry — what a hexagon *is* 2. The three coordinate systems 3. Conversions between systems 4. Neighbors and diagonals 5. Distances 6. Movement range, intersections, and BFS 7. Line drawing 8. Rotation 9. Reflection 10. Rings and spirals 11. Field of view 12. Hex → pixel and pixel → hex 13. Rounding a fractional hex 14. Storing a hex map 15. Wraparound maps 16. Pathfinding 17. A reusable C++ template 18. Practice pr...
Hex neighbor(Hex h, int dir) { return {h.q + DQ[dir], h.r + DR[dir]}; } ```, }; // 0:E 1:NE 2:NW 3:W 4:SW 5:SE (pointy-top) Hex neighbor(Hex h, int dir) { return {h.q + DQ

Full text and comments »

  • Vote: I like it
  • +108
  • Vote: I do not like it

25.
By AkiLotus, history, 8 years ago, In English
Codeforces Round #229 (Div. 2) Editorial [Unofficial] _Since the original data has been lost during the dark days of Codeforces, no version of the editorial has been re-released, and I feel the round itself is quite educational, so I decided to give a try._ [problem:390A] ------------------ <spoiler summary="Approach"> The criterion shows that we can only use either vertical segments or horizontal segments. Since there is no limit on the segments' length, we can see that it's always optimal to use a segment with infinite length (or may be known as a line). We can see that the vertical line $x = a$ will span through every alarm clocks standing at positions with x-coordinate being equal to $a$. In a similar manner, the horizontal line $y = b$ will span through every alarm clocks standing at positions with y-coordinate being equal to $b$. So, if we use vertical lines, the number of segments used will be the number of distinct values of x-coordinates found in the data. Similarly, the number of horizontal segments used will be...
; cost += Dist[x][y]; for (int dir=0; dir<4; dir++) { if (x + dx[dir] < 1 || x, Dist[x+dx[dir]][y+dy[dir]] = Dist[x][y] + 1; Q.push({x + dx[dir], y + dy[dir ]}); Last[x+dx, for (int dir=0; dir<4; dir++) { if (x + dx[dir] < 1 || x + dx[dir] > n) continue; if (y, if (Dist[x+dx[dir]][y+dy[dir]] != 4444) continue;

Full text and comments »

  • Vote: I like it
  • +37
  • Vote: I do not like it

26.
By balbit, history, 5 years ago, In English
Let's Solve Some More Hard Problems! Inspired by ivan100sic's [problem list blog](https://codeforces.me/blog/entry/98630), I'll pick 10 nontrivial-seeming recent POI (Polish Olympiad in Informatics) problems that I haven't solved and track my progress here. It seems to me that POI is better suited for this format as their editorials are quite difficult to find (if possible [at all](https://szkopul.edu.pl/problemset/problem/v2Y2_UW56ENMcbwP22tkTb7a/site/?key=statement)). While Ivan's original challenge was supposed to last an entire year, I'm not nearly as patient, so I won't look for editorials only until February 1st (in just over 2 weeks). Hopefully I'll have completed at least 80% by that time. Until then, GLHF!!! The List: 1. [Multidrink 2013](https://szkopul.edu.pl/problemset/problem/GyDCbdIgFY5FsMa9iIsBl3hf/site/?key=statement) [Solved Jan 15] <spoiler summary="Fun-ness:"> 5/10 <spoiler summary="Comments"> My thought process on this problem went like "ew this is disgusting implementation" => ...
pii flip(pii pt, pii dir) { if (dir.f == -1 && pt.f) { pt.f = 4*m-pt.f

Full text and comments »

Tags pow, odz, eni, abh, ai
  • Vote: I like it
  • +149
  • Vote: I do not like it

27.
By AkiLotus, 8 years ago, In English
Codeforces Round #538 (Div. 2) Editorial *Model solutions are now available.* *[user:GreenGrape,2019-02-10] and I will write more about problem F, including an alternative data structures (still quite tight on time limit) ;)* [problem:1114A] ------------------ Author: [user:Akikaze,2019-02-10], [user:GreenGrape,2019-02-10] Development: [user:Akikaze,2019-02-10], [user:GreenGrape,2019-02-10], [user:neko_nyaa,2019-02-10] Editorialist: [user:Akikaze,2019-02-10] <spoiler summary="Tutorial"> First of all, we can see the grape preference is hierarchically inclusive: the grapes' types Andrew enjoys are some of those that Dmitry does, and Dmitry's favorites are included in Michal's. Let's distribute the grapes to satisfy Andrew first, then to Dmitry, then Michal. If any of the following criteria is not satisfied (which means one of our friends is not happy), then we can immediately say that no distributions are available: - Andrew must have at least $a$ green grapes. So we need, $x \le a$. - Dmitry can ha...
are either of color $c_L$ or $c_R$. We can define $dp \left( L, R, dir \right)$ as the minimum number

Full text and comments »

  • Vote: I like it
  • +148
  • Vote: I do not like it

28.
By karan_garg_12, 19 months ago, In English
Editorial — Dream in Code 25' — by IIIT Lucknow **[Dream In Code '25](https://codeforces.me/contestInvitation/d9fe41b44ce8688f482fa17563ca389c65711a69) – Editorial** *Hosted by Competitive Programming Club, IIIT Lucknow* --- ## Introduction Thank you to everyone who participated in **Dream In Code '25**, held on Codeforces Gym as part of Equinox 2025! We hope you enjoyed the problems and learned something new. This editorial includes detailed explanations and intended solutions for all the problems from the contest. --- ## Problems ### [A. Inversion Spectrum](https://codeforces.me/gym/602694/problem/A) **Setter:** [user:kunwarArjun,2025-05-05] <spoiler summary="Solution"> We need $$ \sum_{x \in X}\bigl(L(x)+R(x)\bigr) \;=\;2\times\bigl|\{\,i<j: X_i>X_j\}\bigr| $$ so it suffices to count the number of inversions in the exit array $X$ and multiply by two mod $10^9 + 7$. There exists a standard way to count inversions in the array using Merge Sort Algorithm. You can also impl...
< dist[nx][ny][nz][dir][new_speedlevel]) { dist[nx][ny][nz][dir][new_speedlevel, ; for(int dir = 0; dir < 6; dir++) { int nx = x + dx[dir]; int ny = y, for(int dir = 0; dir < 6; dir++) { int nx = x + dx[dir]; int ny = y + dy, int new_speedlevel = (dir == lastdir) ? min(speedlevel + 1LL, 3LL) : 0; int move_cost

Full text and comments »

  • Vote: I like it
  • +17
  • Vote: I do not like it

29.
By dapingguo8, 7 months ago, In English
Codeforces Round 1092 (Div. 1, Div. 2, Based on THUPC 2026 — Finals) Editorial We apologize for both the late editorial and the statement leaking issues. Unfortunately, as the problem authors, we never had any chances to prevent the leaking. Still, feel free to downvote if you have dissatisfaction due to these. But what so ever, we hope you can enjoy the problems. [problem:2216A] Idea by [user:Warriors_Cat,2026-04-13] <spoiler summary="Solution"> The method is simple: for $i = k, k - 1, \dots, 1$ successively, we adjust the courses at the $i$-th level of course wish one by one directly to the $(k+1)$-th level. It is easy to check that the adjustment is valid. The number of steps is at most $nk \le 1000$. </spoiler> <spoiler summary="Code(C++)"> ~~~~~ #include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #include <cstdlib> using namespace std; #define ll long long #define rep(i, x, y) for(int i = x; i <= y; ++i) #define per(i, x, y) for(int i = x; i >= y; --i) inline int read(){ int x = 0, f = 1; cha...
]; long long dfs(int dir,int fr,int bk,int S){ int hav=0; if(fr, ][maxn][maxs]; bool g[2][5][maxn][maxs]; long long dfs(int dir,int fr,int bk,int S){ int hav=0

Full text and comments »

  • Vote: I like it
  • +80
  • Vote: I do not like it

30.
By abdude824, 5 years ago, In English
Operating Systems Notes If you are struggling with the right track and a 10-min read for Operating systems from beginning to end, you're at the right place. Even I am not sure where to start, but we would figure it and if you are reading this, I have successfully completed these notes or at least am on right track. Let's start our struggle for OS: ### The Track I found many resources to learn, let's just list all: (Galvin Concise PPTs)[https://www.os-book.com/OS9/slide-dir/index.html]: These were great but I felt that these are a little bit too much, so here are the chapters we would do: 1. Processes 2. Threads 3. Process Synchronization 4. CPU Scheduling Algorithms 5. Deadlocks 6. Main memory 7. Virtual memory 8. Virtual Machines > I am skipping the introduction of OS for now as it was not that important, this is going to be a fast article that works like a last night dose. <spoiler summary="A simple introduction(May skip if you are already familiar)"> An Operating system is like a...
-book.com/OS9/slide-dir/index.html]: These were great but I felt that these are a little bit too much, so

Full text and comments »

  • Vote: I like it
  • +160
  • Vote: I do not like it

31.
By QCFium, 6 years ago, In English
[Tutorial] Subtree lazy propagation on the link-cut tree The link-cut tree is a data structure that can maintain dynamic forest (that is, we can add/remove edges as long as the graph remains a forest) and handle various types of queries efficiently. It can handle not only path aggregation/update queries but also [subtree aggregation queries](https://codeforces.me/blog/entry/67637). Let's go further and try subtree lazy propagation ! Note that there is a limitation of the lazy propagation operator to be used in this link-cut tree trick : invertibility. For example, subtree add query meets this condition, but subtree bitwise-or update doesn't. Alternative ways ------------------ The top tree can perform subtree update queries quite naturally, without requiring invertibility, but it's a bit hard to implement and has a relatively big constant in running time. The euler tour tree can perform subtree update/aggregation queries efficiently but can't handle path queries. Terms ------------------ auxiliary tree : the splay tree used t...
^= 1; rev = false; } } void rotate(int dir) { Node *new_root = ch[!dir]; assert, ; } } void rotate(int dir) { Node *new_root = ch[!dir]; assert(new_root != NONE); if (new_root->ch

Full text and comments »

  • Vote: I like it
  • +56
  • Vote: I do not like it

32.
By fbrunodr, history, 2 years ago, In English
C++ and VSCode setup on macOS ### Problem to be addressed On Linux it is pretty straightforward to set up the debugger for C++ on VSCode. The workflow is: - Write your code - Go to the [Run and Debug] VSCode section - Click on run active file or something similar - Debug your code On macOS you will run into a lot of silly problems, such as: - Can't find `#include<bits/stdc++.h>` - Installed g++ and got the debugger running, buck can't write input to `std::cin` in the integrated terminal, because it says ~~~~~ Build finished successfully. * Terminal will be reused by tasks, press any key to close it. ~~~~~ and then closes the terminal, making it impossible to write to `std::cin`. After some time browsing the internet I found the solution for all those problems and got my setup working just like on linux. ### Solution Let's brake the solution step by step, from a almost brand new macOS. 1. [Install Homebrew](https://brew.sh) 2. Install g++ (`brew install gcc`) 3. Down...
files inside the dir `/opt/homebrew/bin/` by running `ls /opt/homebrew/bin/` on your terminal and from, whatever version is installed; you can see the files inside the dir `/opt/homebrew/bin/` by running `ls, In the same `.vscode` dir create another file called `launch.json` and write this code inside it:

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

33.
By IlyaLos, history, 11 years ago, translation, In English
Разбор Codeforces Round #346 (Div. 2) [659A &mdash; Круглый дом](http://codeforces.me/contest/659/problem/A) Ответом на задачу является формула $((a - 1 + b)$ $mod$ $n$ + $n$) $mod$ $n$ + $1$, где $mod$ $n$ &mdash; операция взятия остатка по модулю $n$. Итоговая временная сложность решения равна $O(1)$. Допускается также итеративное решение, каждый раз перемещающее Васю на 1 подъезд в нужном направлении. Итоговая временная сложность решения равна $O(|b|)$. [659B &mdash; Отбор на олимпиаду](http://codeforces.me/contest/659/problem/B) Будем рассматривать участников каждого региона отдельно. Отсортируем всех участников из региона в порядке невозрастания баллов. Ответ для данного региона неоднозначен тогда и только тогда, когда участников хотя бы трое и баллы второго и третьего участника совпадают. Иначе ответом является пара из первого и второго участников. Итоговая временная сложность решения равна $O(n \log{n})$. [659C &mdash; Таня и игрушки](http://codeforces.me/contest/659/problem/C) Наша зад...
$dir$ is equal to the number before performing a turn $oldDir$ plus one modulo $4$ $(dir \equiv oldDir, the left if and only if the number of direction after performing a turn $dir$ is equal to the number, — $3$. Тогда поворот будет поворотом налево, если число для следующего направления $dir$ равно, , если число для следующего направления $dir$ равно числу предыдущего направления $oldDir$ плюс $1$ по

Full text and comments »

  • Vote: I like it
  • +85
  • Vote: I do not like it

34.
By UTPC_Admin, 2 years ago, In English
UTPC Fall 2024 Contest #1 Editorial Hope you enjoyed our contest! The editorial is below: [A &mdash; Spookeepy](https://codeforces.me/gym/105346/problem/A) Author: [user:porkchops,2024-09-19] <spoiler summary="Solution"> We can use distance formula to calculate the distance from each point in the map to your current location. We return the point with minimum distance. If there are multiple points at the same minimum distance, keep the point with the smallest x-coordinate, and if there is still a tie, keep the point with the smallest y-coordinate (as stated in the problem description). </spoiler> [B &mdash; Ternary Nightmare](https://codeforces.me/gym/105346/problem/B) Author: [user:B-1168,2024-09-19] <spoiler summary="Solution"> The specific mixtures of 0, 1, and 2s are not as significant as the length of contiguous blocks of 0s and 1s (those "contiguous blocks" can have length 0, when between consecutive instances of 2). For example, we can parse the $1201012200120012$ sample into 0-1 blocks of le...
in. Then the state can be defined in terms of $l, r, dir$. Let's use Dijkstra's Algorithm to find, the state can be defined in terms of $l, r, dir$. Let's use Dijkstra's Algorithm to find the

Full text and comments »

  • Vote: I like it
  • +5
  • Vote: I do not like it

35.
By clex, history, 17 months ago, In English
Specialist after 4 contest. Is he cheating? + prof ai cheater 23rd place and 5 more cheaters Yo So apparently I found out this [user:marshadow_ninja,2025-06-13] guy and he gain my suspicion through his code. Problem B: Instant change of coding style, using T instead of tt as his previous [problem A](https://codeforces.me/contest/2118/submission/324084308) submission, variable name starts to get longer. Also this style is very VERY similar to ChatGPT and also in competitive progamming who will like to use caps lock letters and variable i mean it take lot more time [Problem C](https://codeforces.me/contest/2118/submission/324094098) : "onesAbove" array, interesting name tbh. Also the logic and style is the similar to ChatGPT and same thing again can y'all tell me you will prefer writing o_a or oa as variable name if it is used 10+ time in code or you will prefer writing onesAbove as var name. intially_beauty bro i would have used ib as var name wtf use this much bigger names i suppose his hands had potion that make him immune to pain <spoiler summary="onesAbove vs oa...
good is he? Same style as ChatGPT. (using THIS ~~~~~ auto state_id = [&](int i, intdir, int r, ~~~~~ auto state_id = [&](int i, int dir, int r){return (i*2 + dir) * k + r;}; ~~~~~

Full text and comments »

  • Vote: I like it
  • +16
  • Vote: I do not like it

36.
By fcspartakm, history, 11 years ago, In Russian
Разбор задач Технокубок 2016 — Отборочный Раунд 1 ### [problem:648A] Для решения данной задачи насчитаем высоту каждой горы и сохраним ее в массиве $h[]$, где $h[j]$ равно высоте $j$-й горы. Для этого обойдем заданную матрицу, и если элемент, стоящий в строке $i$ и в столбце $j$ (строки и столбцы 0-индексированы), равен звездочке, обновим высоту $j$-й горы: $h[j] = max(h[j], n - i)$. Осталось просто проитерироваться по столбцам от 0 до m &mdash; 2 включительно, и, если текущий столбец равен $j$, обновить величину максимального подъема или максимального спуска величиной $|h[j + 1] - h[j]|$. <spoiler summary="Пример решения"> Основная часть решения: ~~~~~ int n, m; int h[N]; char c; void solve() { cin >> n >> m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> c; if (c == '*') { h[j] = max(h[j], n - i); } } } int maxU = 0, maxD = 0; for (int i = 0; i < m - 1; i++) { int diff = h[i + 1] - h[i]; if (diff > 0) { maxU = max(maxU, diff)...
[] = {0, 0, -1, 1}; char dir[] = {'U', 'D', 'L', 'R'}; void solve() { cin >> n >> m; for, ][ny] = '.'; px = sx, py = sy; sx = nx, sy = ny; cout << dir[i, int dx[] = {-1, 1, 0, 0}; int dy[] = {0, 0, -1, 1}; char dir[] = {'U', 'D', 'L', 'R'};

Full text and comments »

  • Vote: I like it
  • +34
  • Vote: I do not like it

37.
By vishwas_16.0, history, 3 months ago, In English
CC Wing Selection Contest 2026 Editorial CC Wing Selection Contest 2026 ================== [contest:709193] ------------------ </br> [Invitation Link](https://codeforces.me/contestInvitation/6272dbd500a98e5b9fb8fdc43969fd8573242e5a) </br> [Problem A : Terms and Conditions](https://codeforces.me/gym/709193/problem/A) <br> Author : [user:vishwas_16.0,2026-08-12] <spoiler summary="Hint 1"> The input is irrelevant. The required output is fixed and must be printed exactly as given.</spoiler> <spoiler summary="Solution"> This is a direct output problem. We are given a single string as input, but regardless of what the input contains, we must print the four Terms and Conditions exactly as specified in the statement. Since the required output is constant, there is no need to process the input. Just print: You confirm that you are a IIIT Allahabad Batch 2029 student. You understand that providing false information, copying code may result in removal from the wing. You accept that parties wil...
~~~~~ vp dir = { {-1, 0}, {0, 1}, {0, -1}, {1, 0} };, for (auto [dx, dy] : dir) { int nx = x + dx; int ny = y + dy;

Full text and comments »

  • Vote: I like it
  • +11
  • Vote: I do not like it

38.
By CountZero, 5 years ago, In English
[Tutorial] Setting up Windows C++ environment — Microsoft edition Hello. This is kind of continuation of this post https://codeforces.me/blog/entry/102287. In this tutorial I'll try to explain how to write and compile C++ code on Windows, using tools provided by (mostly) Microsoft. I'm going to use latest versions. Terminal ======== First of all, let's install [Windows Terminal](https://www.microsoft.com/store/productId/9N0DX20HK701) and [MS PowerShell](https://www.microsoft.com/store/productId/9MZ1SNWT0N5D). Standart windows command line is just not usable. Let's also install [winget](https://www.microsoft.com/store/productId/9NBLGGH4NNS1) &mdash; this is a package manager similar to, for example, homebrew. Maybe chocolatey is better but, again, this one is developed by Microsoft. Of course Microsoft Store isn't mandatory, you can use any other source for these packages. I'd also suggest to try [starship](https://starship.rs/) command prompt &mdash; very useful tool, supports powershell as well. Compilers and tools ================...
": [ "clangd", "--compile-commands-dir=build" ], "selector": "source.c, -commands-dir=build" ], "selector": "source.c | source.c++ | source.objc | source.objc, . `--compile-commands-dir=build` tells it that this file is located in `build` subdirectory.

Full text and comments »

  • Vote: I like it
  • +19
  • Vote: I do not like it

39.
By arham_doshi, history, 6 years ago, In English
cses graph session editorial(incomplete) I got bored with solving and wanted to do something which is related to cp and also very fun so i decided to write this tutorial.bare me for my bad English . ### how to solve grid problems <spoiler summary="trick"> here is my template to solve grid problems ~~~~~ int dx[]={0,0,1,-1}; int dy[]={1,-1,0,0}; string ds="RLDU"; int n,m; bool possible(int x,int y){ //cout<<n<<" "<<m<<" "<<x<<" "<<y<<" possible"<<endl; return (x<n&&x>=0&&y<m&&y>=0); } ~~~~~ here we cand do just x+dx[i],y+dx[i] to move the four <br> directions and ds helps if we want to record path.<br> we can easily extend it to include four diagonals </spoiler> 1) counting rooms ------------------ <spoiler summary="explanation"> For each unvisited '.' cell we have to make dfs(or bfs)<br> and keep on coloring the visited nodes.We keep track number<br> of dfs by count variable .our answer would be count. </spoiler> <spoiler summary="code"> ~~~~~ void dfs(...
has reached there. You can recreate path using FRM and DIR matrix as I have done in Labyrinth, start bfs from a and try to reach b. We will keep a vector FRM and DIR which will keep, ; dir[nx][ny]=s[i]; //cout<<"("<<<","<<<") ";, ; return 0; } cout<<"YES"<dir[to.x, ; } cout.flush(); */ _init(vis); pair from[n+1][m+1]; char dir[n+1][m+1]; s, >from a and try to reach b. We will keep a vector FRM and DIR which will keep track of the cell

Full text and comments »

  • Vote: I like it
  • +77
  • Vote: I do not like it

40.
By eulmelk, 6 months ago, In English
Code League — National Competitive Programming Contest — Round 2 — Editorial Here is the link to the contest: [Link](https://codeforces.me/contestInvitation/f528fcc29732183e36f82a0adfdc6dbac0743f3f) ### [A. Free Coupon](https://codeforces.me/gym/690685/problem/A) <spoiler summary="Rate the Problem"> - **How good is this problem?** - Very Good - Good - Bad - Very Bad - **How hard is this problem?** - Very Easy - Easy - Hard - Very Hard </spoiler> <spoiler summary="Hint"> Which items should be taken using coupons? <spoiler summary="Answer"> Since a coupon can be used on any item regardless of its price, it is always best to use coupons on the most expensive items. This allows us to spend our coins only on cheaper items. </spoiler> </spoiler> <spoiler summary="Solution"> The problem asks us to find the maximum number of items Abenezer can obtain given $k$ coins, with the offer that every $b$ items bought with coins yiel...

Full text and comments »

  • Vote: I like it
  • +11
  • Vote: I do not like it

41.
By Azret, 12 years ago, In Russian
Разбор задач Интернет-Тура ВКОШП _**Доброго времени суток!**_ **Задача А.** Реализация. **Задача B.** Ладей можно было расставлять по диагоналям. **Задача С.** Пусть города уже отсортированы по возрастанию пары `(население, цена)`. Для простоты будем считать, что у всех городов разное население (при допуске совпадений к доказательству прибавится лишь немного незначительных подробностей). - Можно считать, что сперва мы вербуем людей, а потом завоёвываем города. Пусть из _i_-того города завербовано _x<sub>i</sub>_ людей в лучшем ответе. - Города лучше всего захватывать в порядке _a<sub>i</sub> - x<sub>i</sub>_ (очевидно). - В одном из лучших ответов города надо захватывать в порядке _a<sub>i</sub>_. Пусть это не так. Тогда если мы сперва захватили _i_, прямо следуюшим _j_ и _a<sub>i</sub> > a<sub>j</sub>_, то _x<sub>j</sub> = 0_ (зачем нам кого-то нанимать, если можно весь город захватить бесплатно). "Перекинем" часть закупок из _i_-того города в _j_-тый. Противоречие. (см. пункт 5)) - Пусть тепе...
задачу к кратчайшему пути в графе. Вершинами графа будут состояния (`l1`, `l2`, `dir`), означающие, что, - Либо на как-то перекрестке мы можем повернуть — то есть добавляем ребро из (`l1`, `l2`, `dir`) в, `, `dir`) в (`l1`, `l3`, `dir`), если пересечение прямых `l1` и `l3` находится в нужном направлении, Сведем задачу к кратчайшему пути в графе. Вершинами графа будут состояния (`l1`, `l2`, `dir

Full text and comments »

  • Vote: I like it
  • +32
  • Vote: I do not like it

42.
By arthur_9548, 13 months ago, In English
Editorial: XIII UnB Contest Mirror We hope everyone enjoyed the problems of [contest:106159]! This editorial contains the description of the solutions and their implementation. Feel free to discuss them in the comments! #### Problem A - Author: [user:PedroPacoca,2025-11-05] - Coauthor: [user:duduFreire,2025-11-05] <spoiler summary="Solution"> In this problem, we want to count the number of strings of length $n$ that have at least one occurrence of the given substring. To do this, we will use the Knuth-Morris-Pratt (KMP) algorithm and the automaton constructed from it, with a complexity of $O(m)$. If $n$ were small, we could solve this problem using dynamic programming, calculating, for each $1 \leq i \leq n$, how many ways we can reach state $0 \leq j \leq m$ of the automaton (representing a string with the last $j$ characters equal to the first $j$ of $s$). This solution has $n \cdot m$ states with transitions of the size of the alphabet, resulting in a time complexity of $O(26 \cdot n \cdot m)$, which is...

Full text and comments »

  • Vote: I like it
  • +13
  • Vote: I do not like it

43.
By Not-Afraid, history, 6 years ago, In English
Bash Script for Stress Testing[Code with explanation] Hello Codeforces community. ~~~~~ Tl;dr: The script is specifically for *Unix and can be used to stress test `C++` solutions. It can be easily modified to work with python or java. To use it in windows you can download Ubuntu terminal which is officially available on Microsoft Store and then use it or you can modify the script to work in cmd by changing the .out files to .exe and a bit of syntax for cmd. ~~~~~ **Note**: If you don't want to read this lengthy blog, just go to [this](https://github.com/bhupixb/Stress-Testing-bash-script) repo and follow the instructions of readme. <br> First let me tell you what stress testing is if you don't know, Stress testing is technique using which we can run our solution (which we think might fail/is failing) on a number of random test cases and match it's output with the output of a solution which is a brute force solution or accepted solution of someone else.<br> If you don't know why and when to use stress testing you can use [...
exist in dir $(pwd), exiting..." exit 1 fi done }

Full text and comments »

  • Vote: I like it
  • +52
  • Vote: I do not like it

44.
By gridnevvvit, 13 years ago, translation, In English
Editorial Codeforces Round #203 (Div. 2) ##[problem:350A] Let's $v = min(a_{i}), p = max(a_{i}), c = min(b_{i})$. So, if $max(2*v, p) < c$, then answer is $max(2*v, p)$, else answer is $-1$. Author solution: [submission:4632352] ##[problem:350B] Input data represents a graph, by using a array of parents of every vertex. Because every vertex has at most one parent, we can use following solution: we will go up to parent of vertex $v$ ($prev[v]$) until not found vertex with the outcome degree $\ge 2$. It is better to calculate outcome degrees in advance. After all, we will update the answer. This algorithm works in $O(n)$. Author solution: [submission:4632399] ##[problem:350C] First of all, Let's sort all point by increasing of value $|x_i| + |y_i|$, all points we will process by using this order. We will process each point greedily, by using maximum six moves. Now we want to come to the point $(x,y)$. Let's $x \ne 0$. Then we need to move exactly $|x|$ in the $dir$ direction (if $x < 0$ the dir is $L$...
to come to the point $(x,y)$. Let's $x \ne 0$. Then we need to move exactly $|x|$ in the $dir, )$. Let's $x \ne 0$. Then we need to move exactly $|x|$ in the $dir$ direction (if $x < 0$ thedir is $L

Full text and comments »

  • Vote: I like it
  • +28
  • Vote: I do not like it

45.
By GreatShinobiOwl, history, 2 months ago, In English
Polyman v3: Let an AI Agent Build Your Problem (and Test It Before Polygon Sees It) About ten months ago, [Stop Fighting with Polygon — Create and Test Problems Locally] (https://codeforces.me/blog/entry/148803) was written. It introduced **Polyman**, a CLI for problem setters. You write the validator, generators, checker, and solutions on your own machine. One command, `polyman verify`, generates every test, validates it, and checks that every solution gets the verdict it should. Then `polyman remote push` sends the whole thing to Polygon. Thank you for the upvotes, the issues and the pull requests. A lot has changed since then, so here is what's new. **Upgrade:** ``` npm install -g polyman-cli@latest polyman --version # 3.0.0 ``` There is one breaking change in how generator scripts are written. See **Migrating from v2** at the end; it takes about two minutes. --- ## 1. Polyman is now built for AI agents This is the biggest change. More and more of us write code together with Claude Code, Codex, Cursor or Aider. A problem package is a good...
If you have a problem on Polygon already, the easiest route is `polyman remote pull ./dir

Full text and comments »

  • Vote: I like it
  • +11
  • Vote: I do not like it

46.
By LGM, 16 years ago, In English
Codeforces Beta Round #57 (Div. 2) Hello!<br><br>I am glad to invite you to participate in Codeforces Beta Round #57 (Div. 2).<br>Today's Contest was prepared by <a href="http://www.codeforces.com/profile/aryobarzan">Amir Goharshady</a> and <a href="http://www.codeforces.com/profile/LGM">Me</a>.<br><br>We are thankful to <a href="http://www.codeforces.com/profile/MikeMirzayanov">Mike Mirzayanov</a> , <a href="http://www.codeforces.com/profile/RAD">Artem Rakhov</a> , <a href="http://www.codeforces.com/profile/Gerald">Gerald Agapov</a> , <a href="http://www.codeforces.com/profile/mjn">Mohammad Javad Naderi</a> , <a href="http://www.codeforces.com/profile/mr.ilchi">Saeed Ilchi</a> and Maria Belova.<br><br>Today's contest is dedicated to <a href="http://en.wikipedia.org/wiki/Nasir_al-Din_al-Tusi">Khaje Nasir Tusi</a> (Great Persian mathematician) since today is the national day of engineering in Iran.<br><br><div align="center"><img style="width: 136px; height: 199px;" src="http://upload.wikimedia.org/wikipedia/commons/b/b6...
/b6/Al-Tusi_Nasir.jpeg"> dir="ltr" id=":tu">Today for the first time in Codeforces, dir="ltr" id=":tu">Today for the first time in Codeforces we have Persian statements

Full text and comments »

  • Vote: I like it
  • +31
  • Vote: I do not like it

47.
By drazil, history, 10 years ago, In English
Editorial of Weekly Training Farm 21 **Update** Editorial of PF is published. PA This is a relatively simple problem. We only need to check if the sum of the lengths is larger than $m$ times $60$. 簡單題。判斷所有的歌曲長度加起來有沒有大於 $m$ 的 $60$ 倍。 PB This problem is asking the index of the very next Fibonacci number. The takeaway point is that there is only a small amount of Fibonacci numbers in the range of 32-bits integer. Also, overflow needs to be considered if you choose to use 32-bits integer instead of 64-bits data types. 這題是在問下一個費波那契數列中數字是第幾個。一個小重點是 32 位元整數範圍內的費波那契數列很稀少。另外如果使用 32 位元非 64 位元資料型態的話,那必須考慮溢位的問題。 PC https://en.wikipedia.org/wiki/Great-circle_distance https://zh.wikipedia.org/wiki/大圓距離 PD We binary search the answer. To check if time $T$ is sufficient, we check the maximum flow of the following new constructed graph: Firstly, we split every vertex $v$ in the original graph into $2 \times t$ vertices in the new graph $(v, dir, t)$ where $dir \in {in, out}$ and $t$ is the time index st...
\times t$ vertices in the new graph $(v, dir, t)$ where $dir \in {in, out}$ and $t$ is the time index, graph $(v, dir, t)$ where $dir \in {in, out}$ and $t$ is the time index starting from $1$. Then, we, 首先,對於每個原始圖裡面的點 $v$,我們在新圖裡建立 $2 \times t$ 個點 $(v, dir, t)$,$dir \in {in, out}$ 以及 $t$ 代表從 $1$ 開始的時間點

Full text and comments »

  • Vote: I like it
  • +15
  • Vote: I do not like it

48.
By divyamsingal01, 6 years ago, In English
CSES Mathematics Section Tutorial So I did not find a tutorial for Maths section of CSES on codeforces, so thought of writing one. I have put all my codes on https://github.com/div5252/CSES-Problem-Set. **This tutorial covers 29 questions of Mathematics Section of CSES.** **1. Josephus Queries** <spoiler summary="Tutorial"> We will solve the problem recursively, reducing the problem by at least half at each step. If $k<\frac{n}{2}$, we can see that the answer would be $2k$. Otherwise, we have removed all the even positions. The odd positions can be renamed from $1,2,\dots,\frac{n}{2}$ and we can recursively find the solution for it. And then we can re-map back to our original $n$ by multiplying by $2$ and subtracting $1$. Time complexity is $O(logn)$. </spoiler> <spoiler summary="Code"> ~~~~~ ll f(ll n,ll k) { if(n==1) return 1; if(k<=(n+1)/2) { if(2*k>n) return (2*k)%n; else return 2*k; } ll temp=f(n/2,k-(n+1)/2); if(n%2==1) return 2*temp+1; ...
++) { ld dir=0; for(int f=0;f<4;f

Full text and comments »

  • Vote: I like it
  • +92
  • Vote: I do not like it

49.
By Sarvesh0955, history, 13 months ago, In English
CodePlus Long 2025 Editorial Welcome to the Editorial of CodelPlus Long 2025. CodePlus Long Contest is a 2-day coding competition featuring a mix of educational and challenging problems. It allows participants to learn, practice, and compete to enhance their problem-solving skills. You can attempt the contest [here](https://codeforces.me/contestInvitation/940e1bd9749a95d26fbca52cd74512d1b505f65e). (Many Original and Challenging problems, you can give it a try :) ) The problems were authored and prepared by [user:pranavsingh0111,2025-10-14],[user:Sarvesh0955,2025-10-16],[user:Ragnar21,2025-10-16],[user:rndascode,2025-10-16],[user:ankitgarg2105,2025-5-14],[user:utk_09,2025-8-14]. We would also like to thank, [user:Rishabh_king,2025-10-16] for testing. Author : [user:Sarvesh0955,2025-10-14] <spoiler summary="Problem A"> This problem can be solved in several ways; one approach is as follows: --- ### Graph Construction Construct a new graph ( **nodes n+1 to 2n** ) where all edge weights ar...
>> node_values[i]; } for (int i = 0; i < N - 1; i++) { int u, v; char dir

Full text and comments »

  • Vote: I like it
  • +6
  • Vote: I do not like it

50.
By rndascode, 22 months ago, In English
Editorial For AlgoArena 2025 We at GDG IIITA are extremely delighted to have successfully hosted AlgoArena 2025. We want to extend our heartfelt gratitude to each and every one of you for participating in AlgoArena, our flagship coding event. Your enthusiasm, dedication, and creativity have made this event a remarkable success. We hope you enjoyed solving the questions as much as we enjoyed creating them for you. Question statements are attached below for your reference: [AlgoArena: Year 1 Questions](https://codeforces.me/gym/580154/attachments/download/29620/Statements_Yr_1.pdf) [AlgoArena: Year 2 Questions](https://codeforces.me/gym/580146/attachments/download/29609/Statements_Yr_2.pdf) A: Squid Game ---------------------- Idea:[user:rndascode,2025-01-16] <spoiler summary="Hint 1"> Can you think of extending the logic for a normal stone paper scissor game to get the solution? </spoiler> <spoiler summary="Hint 2"> What if we check for a solution by first retracting the left hand and then ...
>> node_values[i]; } for (int i = 0; i < N - 1; i++) { int u, v; char dir

Full text and comments »

  • Vote: I like it
  • +3
  • Vote: I do not like it

51.
By apjcoder123, history, 7 months ago, In English
Doubt Hi community, I came across below leetcode problem: URL: https://leetcode.com/problems/shortest-path-in-a-grid-with-obstacles-elimination/description/ Statement: You are given an m x n integer matrix grid where each cell is either 0 (empty) or 1 (obstacle). You can move up, down, left, or right from and to an empty cell in one step. Return the minimum number of steps to walk from the upper left corner (0, 0) to the lower right corner (m &mdash; 1, n &mdash; 1) given that you can eliminate at most k obstacles. If it is not possible to find such walk return -1. Below mentioned DFS solution is an AC for the problem My doubt: In my code I just made tiny changes: I called help() for cell at 0,0 instead of cell at grid.size()-1,grid[0].size()-1, and my code fails Note: In my code I updated the implementation (base case and manhattan optimization) of help() accordingly Is the solution dependent on direction of dfs, or the test cases might have been weak ?? class Sol...
condition if(x + dir[0] >= 0 && x + dir[0] < grid.size() && y + dir[1] >=0 && y +dir[1, for(auto dir:dirs){ //DFS valid condition if(x + dir[0] >= 0 && x + dir[0

Full text and comments »

  • Vote: I like it
  • +3
  • Vote: I do not like it

52.
By SpongeCodes, history, 21 month(s) ago, In English
Need help understanding this permutation solution to a problem (Leetcode 3149) Hi, I need help understanding this question solution. The problem is https://leetcode.com/problems/find-the-minimum-cost-array-permutation/ Basically we are given a permutation of 0 to n and have to construct another permutation $res$ that minimizes the function: $$ \sum_{i=0}^{n-1} \left| {\rm res}[i] - {\rm nums}\bigl[{\rm res}\bigl[(i+1)\hbox{ mod } n\bigr]\bigr] \right| $$ Can anyone explain to me the general idea of the solution? I see union find data structure being used and I assume: 1. start with 0 in the permutation because of cyclic property (any optimal answer can be cyclically rotated to have 0 at start) 2. ans[i] = element to follow i in permutation We find the relation between nums[ans[i]] and i and try to 'merge' elements to minimize the absolute difference But i don't understand the check code. What is the dir and need arrays and why do we check !merge(i,i+1). Why is two adjacent nodes having a connection in nums array disqualify the candidat...
absolute difference But i don't understand the check code. What is the dir and need arrays and why do we, difference But i don't understand the check code. What is the dir and need arrays and why do we, ; } if (i > 0 && dir[i - 1] == 0) { continue, auto work = [&](int x, int d) { if (dir[x] >= 0 && dir[x] != d, for (int i = 0; i + 2 < n; i++) { if (need[i] && need[i + 1] && dir[i] == 0, std::vector dir(n - 2, -1); std::vector cant(n - 1);

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

53.
By inkret, history, 8 years ago, In English
All Arpa's source code comments A fully comprehensive list of all of [user:Arpa,2019-01-08]'s various comments in his templates <spoiler summary="Click"> ~~~~~ // God & me // Lost l<3ve is back :P -:~:- // In the name of God. // You are all thing and We're nothing. // Ya Ali! -:~:- //ya mahdi adrekni -:~:- // God & me // Life is ruined and love is lost :'( // @Yazd -:~:- // God & me // Don't forget me, I beg -:~:- //God & me //Damned if AmirAz doesn't take what he wants. -:~:- // God & me // Life is ruined and love is lost :'( // @Yazd // Happy 1300 <3 -:~:- // God & me // Don't forget me ... -:~:- //God & me //..... ...... ..... .... <3 -:~:- // ya mahdi adrekni '-| //contest: To l<3ve m.sina or not to love; This is the problem! //Welcome to new series of "f*** this bloody contest tonight" (upsolving) -:~:- //God & me //Keep calm and go home ;) -:~:- //God & me -:~:- // God & me // I found myself in Love empire // The 1500'th accept ! -:~:- //God & me ...
-:~:- // in the name of god -:~:- // God & me // I found myself in Love empire //Dir residam

Full text and comments »

  • Vote: I like it
  • +40
  • Vote: I do not like it

54.
By A2SV_Group6, history, 19 months ago, In English
A2SV G6 — Round #10 (Editorial) [Here](https://codeforces.me/contestInvitation/a66de5ddf582f7d7ecf373014147caad99234d6b) is the contest link. #### [A. Mahmoud and Ehab and the even-odd game](https://codeforces.me/gym/602812/problem/A) <spoiler summary="Hint 1"> Think about **who starts** the game and **what numbers** each player is allowed to subtract. Mahmoud starts first and can subtract **even** numbers. Ehab goes next and can subtract **odd** numbers. </spoiler> <spoiler summary="Hint 2"> Now consider **what happens depending on the parity of n**. - If `n` is **even**, Mahmoud can subtract `n` on his first turn and leave `n = 0` — Ehab can't play. - If `n` is **odd**, Mahmoud can't subtract the entire `n` (since it's not even), so the game goes longer. </spoiler> <spoiler summary="Hint 3"> Regardless of the number chosen in each turn, the key idea is that **the parity of n determines who makes the last move**. Since they subtract at least 1 each turn, the number of moves is exact...

Full text and comments »

  • Vote: I like it
  • +5
  • Vote: I do not like it

55.
By tweety, history, 11 years ago, In English
Is university degree important? <HTML> <HEAD> <META HTTP-EQUIV="CONTENT-TYPE" CONTENT="text/html; charset=utf-8"> <TITLE></TITLE> <META NAME="GENERATOR" CONTENT="LibreOffice 4.1.6.2 (Linux)"> <META NAME="CREATED" CONTENT="20091123;224100000000000"> <META NAME="CHANGEDBY" CONTENT="Mahmoud Hassan"> <META NAME="CHANGED" CONTENT="20160315;170001200000000"> <META NAME="AppVersion" CONTENT="00.0001"> <META NAME="DocSecurity" CONTENT="0"> <META NAME="HyperlinksChanged" CONTENT="false"> <META NAME="LinksUpToDate" CONTENT="false"> <META NAME="ScaleCrop" CONTENT="false"> <META NAME="ShareDoc" CONTENT="false"> <STYLE TYPE="text/css"> <!-- @page { size: 8.5in 11in; margin: 1in } P { margin-bottom: 0.08in; direction: ltr; widows: 2; orphans: 2 } --> </STYLE> </HEAD> <BODY LANG="en-US" DIR="LTR"> <P STYLE="margin-bottom: 0.14in">I was going to write a short post asking you about your opinion on the importance of university degree but ended up writing a really long text about the educatio...
: 0.08in; direction: ltr; widows: 2; orphans: 2 } --> DIR

Full text and comments »

  • Vote: I like it
  • +144
  • Vote: I do not like it

56.
By iynaur87, history, 6 years ago, In English
I should always use const auto& inside for loops When solving AtCoder Grand Contest 044 Problem B, I wrote some O(n^3) code with n<=500 like: ~~~~~ typedef vector<int> vi; vector<vi> dirs({{0,1}, {0,-1}, {-1,0}, {1,0}}); ... for (auto dir : dirs){ // run O(n^3) times ... } ~~~~~ and get TLE. On my pc it runs within 4900ms. During the contest I have no idea why.(dumb me) After the contest I looked at other people's solution and finally get accepted solution, just add an '&' after 'auto': ~~~~~ for (auto& dir : dirs){ // run O(n^3) times ... } ~~~~~ 480 ms on my pc! 10 times faster! I did more tests: ~~~~~ for (int dd = 0; dd<4; ++dd){ // run O(n^3) times vi dir = dirs[dd]; ~~~~~ 4900 ms ~~~~~ for (int dd = 0; dd<4; ++dd){ // run O(n^3) times vi& dir = dirs[dd]; ~~~~~ 480 ms ~~~~~ vi dir; for (int dd = 0; dd<4; ++dd){ // run O(n^3) times dir = dirs[dd]; ~~~~~ 1800 ms Maybe vector is too big, I tried pair: ~~~~~ vector<pair<int, int>> dirs({{0...
: ~~~~~ typedef vector vi; vector dirs({{0,1}, {0,-1}, {-1,0}, {1,0}}); ... for (autodir, dir : dirs){ // run O(n^3) times ... } ~~~~~, ~~~~~ for (auto dir : dirs) ~~~~~, ~~~~~ for (int dd = 0; dd<4; ++dd){ // run O(n^3) times vi dir = dirs[dd]; ~~~~~, ~~~~~ for (int dd = 0; dd<4; ++dd){ // run O(n^3) times vi& dir = dirs[dd]; ~~~~~, ~~~~~ vector> dirs({{0,1}, {0,-1}, {-1,0}, {1,0}}); for (auto dir : dirs){ // run, ~~~~~ vi dir; for (int dd = 0; dd<4; ++dd){ // run O(n^3) times dir = dirs[dd]; ~~~~~

Full text and comments »

  • Vote: I like it
  • +60
  • Vote: I do not like it

57.
By A2SV_Group7, history, 7 months ago, In English
A2SV G7 Contest Round #13 Editorial [Here](https://codeforces.me/contests/691516) is the contest link #### [A. PolandBall and Hypothesis](https://codeforces.me/gym/691516/problem/A) Idea and preparation: <spoiler summary="Hint"> Since $m$ only needs to be between $1$ and $1000$, can we just guess values for $m$ and check if $n \cdot m + 1$ is composite? Alternatively, is there an algebraic way to force the expression to become a perfect square? </spoiler> <spoiler summary="Solution"> There are two highly effective ways to solve this problem: **Approach 1: Brute Force** Since the constraints are extremely small ($n \le 1000$ and we only need $m \le 1000$), the maximum number we will ever check is $1000 \times 1000 + 1 \approx 10^6$. We can simply loop $m$ from 1 to 1000, calculate $val = n \cdot m + 1$, and check if $val$ is prime in $O(\sqrt{val})$ time. The first $m$ that yields a composite number is our answer. **Approach 2: $O(1)$ Math (Forcing a Square)** If we can make $n \cdot m + 1$ equal...

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

58.
By rohantrix, history, 5 years ago, In English
CSES Labyrinth TLEs in Java and Python [SOLVED] Both the codes in Java and Python TLE on CSES for same test cases (7-10). Please help me resolve this issue. **Java: [WORKING NOW]** ```java static int endi, endj; static void solve() throws IOException{ StringTokenizer st; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); BufferedWriter output = new BufferedWriter(new OutputStreamWriter(System.out)); st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); char mat[][] = new char[n][m]; char dir[][] = new char[n][m]; fill2D(dir, '#'); int si = 0, sj = 0; for (int i = 0; i < n; i++) { st = new StringTokenizer(br.readLine()); mat[i] = st.nextToken().toCharArray(); for (int j = 0; j < m; j++) { if (mat[i][j] == 'A') { si = i; ...
>= m || mat[nx][ny] == '#')) { q.offerLast(new int[]{nx,ny}); dir[nx, ()); char mat[][] = new char[n][m]; char dir[][] = new char[n][m]; fill2D(dir, }); dir[nx][ny] = 'U'; mat[nx][ny

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

59.
By Egor, 16 years ago, translation, In English
Contest helper <span class="Apple-style-span" style="font-family: verdana, arial, sans-serif; font-size: 12px; line-height: 20px; ">Here is an early alpha version of Contest helper plug-in for Intelli Idea</span><div style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; font-family: verdana, arial, sans-serif; font-size: 12px; line-height: 20px; "><br></div><div style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; font-family: verdana, arial, sans-serif; font-size: 12px; line-height: 20px; ">What this plug-in does:</div><div style="margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px; padding-top: 0px; padding-right: 0px; padding-bottom: 0px; padding-left: 0px; font-family: verdana, arial, sans-serif; font-size: 12px; line-height: 20px; "><ul style="margin-top: 0.5em; margi...
: normal; ">%user dir%\.IntelliJIdea10\config\plugins

Full text and comments »

  • Vote: I like it
  • +23
  • Vote: I do not like it

60.
By qwerty29, history, 6 years ago, In English
Help needed with Problem E: Directing Edges from div 3 656 Question: we are given a graph with some edges non directed. we have to find the direction of those edges such that the graph remains acyclic. My approach: we have to find the ordering of the visit for each node (topological order). This should be the order for the remaining order as well. Problem: The below solution is getting TLE. I am not sure where it's failing. the complexity should be the order of the number of nodes in the graph. Thank you! ~~~~~ #include <bits/stdc++.h> #define all(v) (v).begin(),(v).end() #define f first #define s second using namespace std; vector<vector<int>> adj; vector<int> order; vector<bool> visited; void dfs(int u){ for(int v : adj[u]){ if(!visited[v]){ visited[v] = true; dfs(v); } } order.push_back(u); } int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while(t--){ order.clear(); adj.assign(200001, vect...
(200001,false); int n, m; cin >> n >> m; int dir, u, v; vector, ){ int dir = edges[i][0]; int u = edges[i][1]; int v = edges, dir, u, v; vector> edges; for(int i=0;i> dir

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

61.
By arnav2004, history, 6 years ago, In English
Unexpected behaviour in c++ (Output possibly in hexadecimal) I was solving problem C of Educational Round 109 which was held yesterday.[The link to the question](https://codeforces.me/contest/1525/problem/C). Here is my code: ~~~~~ #include <bits/stdc++.h> using namespace std; using ll = long long; using pii = pair<int,int>; const int INF = 1e9; const int MOD = 1e9+7; struct point{ int x,idx; char dir; }; int n,m; int ans[300005]; bool cmp(point a,point b){ return a.x<b.x; } void helper(vector<point>&v){ sort(v.begin(),v.end(),cmp); for(auto i:v) cout<<i.dir<<endl; deque<point>right,left; for(int i = 0;i<v.size();i++){ if(v[i].dir=='R') right.push_back(v[i]); else{ if(!right.empty()){ point topmost = right.back(); right.pop_back(); int dist = (v[i].x - topmost.x)/2; ans[v[i].idx] = dist; ans[topmost.idx] = dist; } else left.push_back(v[i]); } } while(left.size()>=2){ point l = left.front(); left.pop_front(); point r = left.front(); left....
,int>; const int INF = 1e9; const int MOD = 1e9+7; struct point{ int x,idx; char dir; }; int, . But after sorting the points when I print some arbitrary points dir (direction) the output comes out, ; const int MOD = 1e9+7; struct point{ int x,idx; char dir; }; int n,m; int ans[300005, I made a struct point which contains x(coordinate of point), idx(index of point) anddir(direction

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

62.
By RodionGork, 15 years ago, In Russian
"Уличная магия" в массы <p>В посте об <a href="http://codeforces.me/blog/entry/3069">уличной магии</a> коллега затронул тему, которая быть может не всем близка, не всем понятна и т.п.<br /><br />Не могу ответственно сказать, очень ли важны эти тайные знания, но думаю не будет беды, если попробую показать пару фокусов, благодаря которым эта &quot;магия&quot; может быть доступна каждому.<br /><br />Напишем программу &quot;Хелло Ворлд&quot;, такого размера, что выводимый текст будет занимать в ней больше половины!<br /><br />Как и вся магия, она будет плохо переносима, но под дос и винды работать будет. Что нам понадобится? Утилита debug.exe - в современных виндах она живёт в c:\windows\system32 - это примитивный дебаггер который остался там рудиментарно с самых старинных версий доса... Кое для чего он ещё может пригодиться! (хотя для серьёзной разработки на ассемблере нужен нормальный компилятор - ну а простенькие вещи и в дебаггере можно накидать)<br /><br />Если вы работаете из под linux, как я, то вам понадо...
C:\>dir hw.com HW COM , />Hello C:\> Проверьте её размер: C:\>dir hw.com HW

Full text and comments »

  • Vote: I like it
  • +46
  • Vote: I do not like it

63.
By Arpa, history, 7 years ago, In English
Call for problem setting on HackerEarth **UPDATE: I'm no longer contest coordinator at HackerEarth, contact [email protected] for proposing problems** **Please read [this](https://codeforces.me/blog/entry/73839) blog as an update.** Hi everyone. I want to describe the process to become a problem setter on HackerEarth. I'm eager to see new problem setters want to prepare contests. It's a great experience for every coder to hold a contest at least once. The first time when I prepared a contest (I was fifteen at that time, a high schooler student!) it was so sweet for me that I continued preparing problems on Codeforces, CodeChef, HackerEarth, Quera, Iran Olympiad of Informatics Finals and several more. Then I worked for 1.5 years in [Quera](https://quera.ir) as the contest coordinator, which was great. I'm continuing my job &mdash; Contest Coordinating &mdash; on HackerEarth from January. We have three algorithmic contest every month, here is the table: <table> <tr> <th>Contest</th> <th>Number o...
dir="ltr" style="margin-left: 0px; margin-right: 0px; width

Full text and comments »

  • Vote: I like it
  • +55
  • Vote: I do not like it

64.
By ramchandra, 6 years ago, In English
Splay tree tutorial This tutorial is about the splay tree, a self-balancing binary search tree. ##### Key features: * $O(\log n)$ amortized operations. * $O(n)$ construction time complexity (you can simply build a binary search tree) * Memory-efficient: no additional space needed apart from the binary search tree. The key idea behind the splay tree is the splay function, which rotates nodes so as to balance the tree. Since this consists only of tree rotations, this does not affect the binary search tree ordering. ##### Tree rotation A tree rotation inverts the relationship between a parent and a child node, _without_ affecting the in order traversal of the binary search tree. See the animation below. ![Tree rotation](/predownloaded/bc/87/bc87ae5e4f0a40597786b727489d11a148522560.png) ([Animation source](https://commons.wikimedia.org/wiki/File:Tree_rotation_animation_250x250.gif): Wikipedia user Tar-Elessar, licensed under CC-BY-SA 4.0) ##### Splay operation During a splay s...
!(*this == oth);} private: template dir> void advance() { if (node->child[1, iterator oth) const {return !(*this == oth);} private: template dir> void advance

Full text and comments »

  • Vote: I like it
  • +107
  • Vote: I do not like it

65.
By SaucyFries69, history, 7 months ago, In English
[Tool] dsastress: A Rust-based CLI for Stress Testing & Minimizing Failing Cases **Hello Codeforces!** **We’ve all been there:** your solution passes the sample tests, but you get Wrong Answer on Test 4. You know there’s a bug, but the system test cases are huge and impossible to debug by hand. I’ve created a small, **high-performance CLI tool** called **dsastress** to automate the classic stress-testing workflow. What is dsastress? ------------------ It’s a Rust-based tool that repeatedly runs a generator, compares your solution against a brute-force (reference) implementation, and stops the moment it finds a mismatch. Key Features: ------------- Language Agnostic: Works with Python, C++, Rust, Java, or any CLI-executable. Automatic Minimization: Uses a ddmin-style algorithm to shrink a giant failing input into the smallest possible "repro" case. Reproducible Seeds: Passes DSASTRESS_SEED to your generator so you can recreate specific failures. Artifact Saving: Automatically saves input.txt, expected.txt, and got.txt into folders for ...
brute.py" \ --tests 1000 \ --minimize \ --save-dir failing_cases ~~~~~, " \ --reference "python3 brute.py" \ --tests 1000 \ --minimize \ --save-dir failing_cases

Full text and comments »

  • Vote: I like it
  • -3
  • Vote: I do not like it

66.
By Fefer_Ivan, 15 years ago, In Russian
Удаление мусора после использования Visual Studion 2010 <p>Добрый день, Codeforces.</p><div><br></div><div>Сегодня я обнаружил, что папка, в которой я храню весь олимпиадный код занимает 2,5 Гб. Причем 97% этого места занимают какие-то непонятные файлы, которые оставляет после себя Visual Studio.&nbsp;</div><div>Следующий скрипт на Python уменьшил размер упомянутой выше папки до 55 Мб:</div><div><br></div><div><div><div>import re, os</div><div>dir = "D:\\Projects\\Olymp\\"</div><div><br></div><div>pattern = "(.+\.txt)|(.+\.cpp)|(.+\.java)|(.+\.py)|(.+\.h)"</div><div>goodFile = re.compile(pattern)</div><div><br></div><div>for root, dirs, files in os.walk(dir):</div><div>&nbsp; &nbsp; for name in files:</div><div>&nbsp; &nbsp; &nbsp; &nbsp; fullname = os.path.join(root, name)</div><div>&nbsp; &nbsp; &nbsp; &nbsp; if goodFile.match(name):</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print "Kept " + fullname</div><div>&nbsp; &nbsp; &nbsp; &nbsp; else:</div><div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; os.remove(fullname)</div><div>&nbsp...
размер упомянутой выше папки до 55 Мб: import re, osdir, dir = "D:\\Projects\\Olymp\\", for root, dirs, files in os.walk(dir):

Full text and comments »

  • Vote: I like it
  • +1
  • Vote: I do not like it

67.
By mehmet, 12 years ago, In English
Why I am getting run time error? Hi, I am trying to solve [Drazil and Tiles](http://codeforces.me/contest/515/problem/D) problem. But in the 7th input which is 3 3<br/> .*.<br/> ...<br/> .*.<br/> I am getting run time error. When I try that input in my PC, it works well and gives correct answer. I also tried many other inputs in that question and my code works correctly for all input. That is my code and I will really appreciate if you can help me. ~~~~~ #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <vector> #include <queue> #define MAX 2002 #define FOR(i,j,k) for(int i=j;i<k;i++) #define pint pair<int,int> #define mp(a,b) make_pair(a,b) #define fi first #define se second using namespace std; int N,M; string A[MAX]; int dir[4][2]={-1,0,1,0,0,1,0,-1}; int K[MAX][MAX]; int finish; void read(){ cin >> N >> M; FOR(i,0,N){ cin >> A[i]; FOR(j,0,M) finish += (A[i][j] == '*'? 1:0 ); } } int findNumberofAdj(int i,int j)...
first #define se second using namespace std; int N,M; string A[MAX]; int dir [4][2, int N,M; string A[MAX]; int dir[4][2]={-1,0,1,0,0,1,0,-1}; int K[MAX][MAX]; int finish;, int adj = 0; FOR(y,0,4){ int a = dir[y][0]+i, b = dir[y][1]+j; if(a>=0 && a=0 && b, mark(x,adj); FOR(y,0,4){ int a = dir[y][0]+x.fi, b = dir[y][1]+x.se; if(findNumberofAdj, pint findAdj(int i,int j){ FOR(y,0,4){ int a = dir[y][0]+i, b = dir[y][1]+j; if(a>=0 && a

Full text and comments »

  • Vote: I like it
  • +2
  • Vote: I do not like it

68.
By ramentaneja, 3 years ago, In English
How slow is struct in the context of this code? Hi everyone, I started solving the CSES problemset. I was on problem 2.Labyrinth of the graph problems (https://cses.fi/problemset/task/1193/) While my approach was BFS as the other A/Cs. Their implementation used various arrays, while mine used a user-defined struct. I was unable to find any differences in their and mine "approach" as such, just the implementation was different. Is this the reason why I am getting a **Time Limit Exceeded** error or is there some other issue with my implementation? # My Code: ``` #include <bits/stdc++.h> using namespace std; struct Cell { int i; int j; string steps; }; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); ll n, m; cin >> n >> m; char arr[n][m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> arr[i][j]; } } queue<Cell> q; bool check = false; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (arr[i][j] == 'A') { q...
, 1, -1}; int d2[] = {1, -1, 0, 0}; char dir[] = {'R', 'L', 'D', 'U'}; bool ansfound = false, ; } } string ans = ""; int d1[] = {0, 0, 1, -1}; int d2[] = {1, -1, 0, 0}; char dir[] = {'R', 'L

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

69.
By aditya.agrawal.a.777, history, 3 years ago, In English
Help with Mock CCC Junior 5 question—further optimisation than BFS needed? Hi, I couldn't find a better place to post this—if you know of a more suitable forum please let me know. Mock CCC 2024 Junior 5, Mathland—https://dmoj.ca/problem/mccc6j5 For this problem, I implemented a BFS solution which explores the states for the shortest path. ~~~~~ #include <iostream> #include <queue> #include <unordered_set> #include <tuple> #include <utility> using namespace std; int n, k; char m[800][800]; vector<pair<int, int>> dirs = { {-1, 0}, {0, 1}, {1, 0}, {0, -1} }; struct HashTuple { size_t operator()(const tuple<pair<int, int>, int, int>& tuple) const { size_t hash = 0; hash_combine(hash, get<0>(tuple).first); hash_combine(hash, get<0>(tuple).second); hash_combine(hash, get<1>(tuple)); hash_combine(hash, get<2>(tuple)); return hash; } private: template <class T> void hash_combine(size_t& seed, const T& value) const { hash<T> hasher; s...
') { for (pair &dir: dirs) { pair next = make_pair(coord.first+dir.first

Full text and comments »

70.
By zhenghaishu, history, 9 years ago, In English
Codeforces Good Bye 2017 Div.2 908A,B #[A. New Year and Counting Cards] ##Problem Statement http://codeforces.me/contest/908/problem/A ##Analysis For letter, only vowel need to know the digit in the other side. For digit, only odd number need to know the letter in the other side. ##Code ``` #include <iostream> #include <string> using namespace std; #define MAX 50 int main() { int cnt = 0; string s; cin >> s; for(int i = 0; i < s.length(); i++) { if('a' <= s.at(i) <= 'z') { if('a' == s.at(i)|| 'e' == s.at(i) || 'i' == s.at(i) || 'o' == s.at(i) || 'u' == s.at(i)) { cnt++; } } if('0' <= s.at(i) <= '9') { if('1' == s.at(i) || '3' == s.at(i) || '5' == s.at(i) || '7' == s.at(i) || '9' == s.at(i)) { cnt++; } } } cout << cnt; } ``` #[B. New Year and Buggy Bot] ##Problem Statement http://codeforces.me/contest/908/problem/B ##Analysis (1) Bob forgot to actually assign the directions to digits, so there are 24 mapping relat...
enum Dir{DOWN, UP, RIGHT, LEFT}; const int maxn = 50; char grid[maxn][maxn]; int n, m; // n

Full text and comments »

  • Vote: I like it
  • +4
  • Vote: I do not like it

71.
By anujnaruka02, history, 3 years ago, In English
Need help in cses problem Labyrinth(Graph) [Problem link](https://cses.fi/problemset/task/1193) My solution is giving wrong output. Any suggestions to help me in this. My code is as follows &mdash; ~~~~~ int main(){ int n,m; cin>>n>>m; vector<vector<char>> v(n,vector<char>(m)); vector<vector<int>> vis(n,vector<int>(m,0)); vector<vector<int>> prevs(n,vector<int>(m)); queue<pair<int,int>> q; pair<int,int> start,end; int delrow[] = {-1,0,1,0}; int delcol[] = {0,1,0,-1}; string dir = "URDL"; for(int i = 0; i<n; i++){ for(int j = 0; j<m; j++){ cin>>v[i][j]; if(v[i][j] == 'A'){ start = {i,j}; } else if(v[i][j] == 'B'){ end = {i,j}; } } } q.push({start.first,start.second}); vis[start.first][start.second] = 1; while(!q.empty()){ int row = q.front().first; int col = q.front().second; q.pop(); for(int i = 0; i<4; i++){ int nrow = row + de...
> start,end; int delrow[] = {-1,0,1,0}; int delcol[] = {0,1,0,-1}; string dir, cout << steps.size() << endl; for(auto it : steps){ cout << dir[it]; } cout, int delrow[] = {-1,0,1,0}; int delcol[] = {0,1,0,-1}; string dir = "URDL";

Full text and comments »

  • Vote: I like it
  • +8
  • Vote: I do not like it

72.
By yesbutno1685, history, 6 years ago, In English
Help with TLEs I have a question on this question: [https://codeforces.me/problemset/problem/1409/E](https://codeforces.me/problemset/problem/1409/E) I am getting a TLE on test five (or when n hits its maximum value). My code gives the correct answer, given infinite amount of time, I just need help on figuring out why it TLEs. From my knowledge, all I do is binary search and do a linear scan, so that's about nlgn time. However, when I submit it, it does not run in time, so I suspect that there is something that I am not catching. I've tried for a long time and still could not figure out why my code is TLE-ing. I hope you guys can help me out Thanks in advance! code (in java): [https://codeforces.me/contest/1409/submission/93014244](https://codeforces.me/contest/1409/submission/93014244) <spoiler summary="Code"> ~~~~~ import java.io.*; import java.util.*; public class twoPlatforms { static int t; static int n, k; static int[] x; public static void main(...
+ rLength); } return ans; } static int binSearch(int target, int dir, binSearch(int target, int dir){ int l = 0, r = n; int res = (dir == 1) ? 0

Full text and comments »

  • Vote: I like it
  • +3
  • Vote: I do not like it

73.
By Kevin114514, history, 4 years ago, In English
CodeForces Round 872(Div. 1&2) Editorial ## A. LuoTianyi and the Palindrome String Consider the substring of $s$ from the second character to the last, or $s_2s_3\cdots s_n$. If it's not palindrome, then the answer must be $n-1$. What if it's palindrome? This implies that $s_2=s_n$, $s_3=s_{n-1}$, and so on. Meanwhile, the fact that $s$ is palindrome implies $s_1=s_n$, $s_2=s_{n-1}$, etc. So we get $s_1=s_n=s_2=s_{n-1}=\cdots$ or that all characters in $s$ is the same. In this situation, every subsequence of $s$ is palindrome of course, so the answer should be $-1$. <spoiler summary="Code"> ```cpp #pragma GCC optimize(3,"Ofast","inline") #pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2") #include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> //#define ll int #define ft first #define sd second //#define endl '\n' #define pb push_back #define ll long long #define pll pair<ll,ll> #define no cout<<"NO"<<'\n' #define no_ cout<<"No"<<'\n' #def...
]={{0,1},{1,0}}; int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}}; int dir3[6][3]={{0,0,1},{0,0,-1},{0,1,0

Full text and comments »

  • Vote: I like it
  • +74
  • Vote: I do not like it

74.
By nerd, 15 years ago, In English
Night of al-Qadr <div style="text-align: center;"><span class="Apple-style-span" style="color: rgb(70, 98, 214); font-weight: bold; font-size: x-large; ">Night of al-Qadr</span></div><div style="text-align: center;"><span class="Apple-style-span" style="color: rgb(70, 98, 214); font-weight: bold; font-size: x-large; "><br></span></div><div style="text-align: center;"><span class="Apple-style-span" style="color: rgb(70, 98, 214); font-weight: bold; font-size: x-large; "><span class="Apple-style-span" style="color: rgb(0, 0, 0); font-weight: normal; font-size: medium; "><table dir="ltr" bordercolor="#111111" height="1" cellspacing="0" cellpadding="0" width="100%" border="0" style="border-collapse: collapse; " id="table34"><tbody><tr><td valign="top" width="59%" height="1"><p align="left" style="line-height: 24px; margin-top: 5px; margin-right: 6px; margin-bottom: 5px; margin-left: 6px; "><span style="font-size: 12pt; font-family: 'Times New Roman'; ">The night of</span><span dir="rtl" style="font-size: 1...
); font-weight: normal; font-size: medium; ">dir="ltr" bordercolor="#111111" height="1" cellspacing, ="color: rgb(0, 0, 0); font-weight: normal; font-size: medium; ">dir="ltr" bordercolor="#111111, dir="ltr" width="100%" colspan="2" height="31">

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

75.
By t3jtex, 11 months ago, In English
a competetive programming tester idk if there are any good testers, so i made my own. Stress testing: ```bash tosts stress \ --number 1000 \ --timelimit 100 \ ./gen \ ./sol1 \ ./sol2 ``` Running on pregenerated tests: ```bash tosts run \ --in-dir tests/in \ --out-dir tests/out \ --in-ext in \ --out-ext out \ --timelimit 100 \ ./sol ``` Generating tests: ``` tosts generate \ --in-dir tests/in \ --out-dir tests/out \ --in-ext in \ --out-ext out \ --number 1000 \ ./gen \ ./sol ``` https://github.com/Tejtex/tosts2 https://crates.io/crates/tosts Installation: ``` cargo install tosts ```
pregenerated tests: ```bash tosts run \ --in-dir tests/in \ --out-dir tests/out \ --in, ``` tosts generate \ --in-dir tests/in \ --out-dir tests/out \ --in-ext in \ --out, ```bash tosts run \ --in-dir tests/in \ --out-dir tests/out \ --in-ext in \ --out

Full text and comments »

  • Vote: I like it
  • +2
  • Vote: I do not like it

76.
By zamazan4ik, 12 years ago, In Russian
Проблемы с решением одной интересной задачи Доброго времени суток! Имеются проблемы с задачей.Предыдущую тему удалил из-за другой проблемы, возникшей с этой задачей. Вот ссылка (задача С, Турнир) [Your text to link here...](http://informatics.mccme.ru/py-source/source/dir/16727) Вот само условие. Для тех, кто не хочет переходить по ссылке : В турнире по хоккею участвовало K команд, каждая сыграла с каждой по одному матчу. За победу команда получала 2 очка, за ничью – 1, за поражение – 0 очков. Известно, сколько очков в итоге получила каждая команда, однако результаты конкретных матчей были утеряны. Требуется восстановить одну из возможных турнирных таблиц. Входные данные В первой строке входных данных содержится одно натурально число K, не превосходящее 100 – количество команд. Во второй строке задаются через пробел K целых неотрицательных чисел, не превосходящих 2(K–1), – количество очков, набранных командами, занявшими первое, второе, …, K-е места соответственно (то есть каждое следующее число не больше предыдущег...
://informatics.mccme.ru/py-source/source/dir/16727)

Full text and comments »

  • Vote: I like it
  • -27
  • Vote: I do not like it

77.
By laurenceHR, 15 years ago, In English
reading easily PHP input Hi peopLe! ... i like code in PHP... and for read fast and easily the input I have created a simple Class... template.min.php ~~~~~ <?php error_reporting(0); //////////////////////// Class For Read Input --- @laurenceHR [02/2012] //////////////////////////////////////////////////////////// class stdIn{var $ntxt = 0;var $nline = 0;var $arr_txt;var $arr_line;var $linex;var $liney; function stdIn($local = false){if($local){$dir = fopen("input.txt", 'r');}else{$dir = fopen("php://stdin", 'r');} $datatxt = stream_get_contents($dir);$del = Array("\n","\r","\n\r");$data = explode("\n",$datatxt); $il = 0;$id = 0; foreach($data as $line){if(strlen($line) > 0){$line = str_replace($del,'',$line);$dataex[] = $line;$text = explode(" ",$line); foreach($text as $txt){$arr_txt[] = $txt;$this->linex[$id] = $il;$this->liney[$il] = $id;$id++;}}$il++;}$this->arr_line = $dataex;$this->arr_txt = $arr_txt;} function G(){$ret = $this->arr_txt[$this->ntxt++];$this->nline = $this->linex[$this->nt...
($local){$dir = fopen("input.txt", 'r');}else{$dir = fopen("php://stdin", 'r');} $datatxt, ; function stdIn($local = false){if($local){$dir = fopen("input.txt", 'r');}else{$dir = fopen("php://stdin

Full text and comments »

  • Vote: I like it
  • +4
  • Vote: I do not like it

78.
By Noob-ita-coder, history, 7 years ago, In English
Solution to import error of Pbds in windows If any like me get this error while importing the Pbds in #includes.. I got error importing this -> #include<ext/pb_ds/assoc_container.hpp> Error was "cannot open source file hash_standard_resize_policy_imp.hpp ". Fix go to the dir -> C:\MinGW\lib\gcc\mingw32\8.2.0\include\c++\ext\pb_ds\detail\resize_policy There u will see a file similar to -> "hash_standard_resize_policy_imp.hpp0000644" Rename it to hash_standard_resize_policy_imp.hpp and now it worked for me . I don't know the real reason why the file was weirdly name before if someone knows plz comment down below and tell. Hope this helps.
hash_standard_resize_policy_imp.hpp ". Fix go to the dir -> C:\MinGW\lib\gcc\mingw32\8.2.0\include\c++\ext\pb_ds, Fix go to the dir -> C:\MinGW\lib\gcc\mingw32\8.2.0\include\c++\ext\pb_ds\detail\resize_policy

Full text and comments »

  • Vote: I like it
  • +17
  • Vote: I do not like it

79.
By ego_for_success, history, 2 years ago, In English
Finding Paths in a Labyrinth: A C++ Solution ~~~~~ #include <bits/stdc++.h> #define ll long long #define endl "\n" using namespace std; int n, m; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin >> n >> m; vector<vector<char>> v(n, vector<char>(m)); vector<vector<int>> vis(n, vector<int>(m, 0)); vector<vector<pair<int, int>>> par(n, vector<pair<int, int>>(m, {-1, -1})); pair<int, int> st, ed; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> v[i][j]; if (v[i][j] == 'A') { st = {i, j}; } if (v[i][j] == 'B') { ed = {i, j}; } } } queue<pair<int, int>> q; q.push(st); vis[st.first][st.second] = 1; while (!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); if (x == ed.first && y == ed.second) break; for (auto [dx, dy, dir] : vecto...
; q.pop(); if (x == ed.first && y == ed.second) break; for (auto [dx, dy, dir, for (auto [dx, dy, dir] : vector>{{1, 0, 'D'}, {-1, 0, 'U'}, {0, 1, 'R'}, {0

Full text and comments »

  • Vote: I like it
  • -2
  • Vote: I do not like it

80.
By ahmed_aly, 16 years ago, In English
Statistics about Google Code Jam Tools website <p>Hi everyone,<br> <br> Here are some notes about <a href="http://ahmed-aly.com/CodeJamTools/">GCJ tools website</a> during round 1A:<br> <br> 1- 191,538 database queries were executed during the contest.<br> 2- The final result for this round is available now.<br> 3- The live scoreboard had some bugs during the contest, but everything is fixed now.<br> 4- I spent more than half of the contest debugging and fixing bugs in the live scoreboard.<br> 5- The whole scoreboard was updated 839 times during the contest.<br> 6- The average time for each single update was 10 seconds.<br clear="all"> <br> -- <br> </p><div dir="ltr">Best Regards,<br>Ahmed Aly<br></div> <div dir="ltr"><br></div> <div dir="ltr"><a href="http://www.ahmed-aly.com/" target="_blank">www.ahmed-aly.com</a><br> <br> </div>
dir="ltr"> , dir="ltr">Best Regards, Ahmed Aly , dir="ltr">www.ahmed-aly.com <http://www.ahmed-aly.com/>

Full text and comments »

  • Vote: I like it
  • +17
  • Vote: I do not like it

81.
By humblefOOOol, history, 6 years ago, In English
Little help in SPFA algorithm for negative cycle in dir graph I am facing a small doubt in SPFA problem. My algorithm not working for some test cases Code: ~~~~~ bool SPFA(int source) //Returns true if there is a negative cycle reachable from source { queue<int> q; for(int i=0;i<=n;i++) { cnt[i]=0; dist[i]=INF; inqueue[i] = false; } dist[source]=0; q.push(source); inqueue[source]=true; while(!q.empty()) { int v=q.front(); q.pop(); inqueue[v]=false; for(auto edge:g[v]) { int to=edge.first; int w=edge.second; if(dist[v] + w < dist[to]) { dist[to] = dist[v] + w; //dist[to] = max(dist[to], -INF); if(!inqueue[to]) { q.push(to); inqueue[to]=true; cnt[to]++; if(cnt[to]>n){ return true; } } } } } return false; } Here in my code for a test case : N = 4 src = 1 u v w 19 20 -36 ...
Little help in SPFA algorithm for negative cycle in dir graph

Full text and comments »

  • Vote: I like it
  • -3
  • Vote: I do not like it

82.
By avirammagen11, history, 10 years ago, In English
Settlers of Catan nwerc 2009 help can someone please explain me how to solve https://icpcarchive.ecs.baylor.edu/external/46/4616.pdf i found this solution ~~~~~ /* NWERC 2009 solution by Jaap Eldering * Problem: Settlers of Catan */ using namespace std; #include <iostream> #include <vector> #include <map> const int totres = 5; const int dx[6] = { 1, 0,-1,-1, 0, 1 }; const int dy[6] = { 0, 1, 1, 0,-1,-1 }; struct point { int x, y; point(int _x, int _y): x(_x), y(_y) {} point next(int d) { point res = *this; res.x += dx[d]; res.y += dy[d]; return res; } }; int operator <(point a, point b) { if ( a.x!=b.x ) return a.x<b.x; return a.y<b.y; } int main() { int nruns; cin >> nruns; for(int run=1; run<=nruns; run++) { map<point,int> mapres; vector<int> nres(5); int n; cin >> n; if ( n==1 ) { cout << "1\n"; continue; } point start(0,0); mapres[start] = 0; nres[0]++; int i = 1, dir = 2; point curr(1,0); f...
; } point start(0,0); mapres[start] = 0; nres[0]++; int i = 1, dir = 2; point curr(1,0, int i = 1, dir = 2; point curr(1,0); for(; idir+1, ~~~~~ i can't understand how the dir array and points work. please help =]

Full text and comments »

  • Vote: I like it
  • 0
  • Vote: I do not like it

83.
By wechicken456, history, 5 years ago, In English
CSES Graph — Labyrinth I'm trying to use BFS to solve CSES &mdash; Labyrinth problem: [Problem statement](https://cses.fi/problemset/task/1193/) I got accepted for most of the test cases, but runtime error for 3 test cases (case 9,10,13). When I tried running it locally with test case 13, the process just got killed: ~~~~~ [1] 8260 killed ./a.out < test_input.txt ~~~~~ Please help me understand what went wrong and how to optimize my solution. This is my solution: ~~~~~ const int maxN = 1e3; int n, m,x; bool visited[maxN + 3][maxN + 3]; void solve(){ cin >> n >> m; char x; pair<int, int>start; pair<int, int>end; vector<vector<int>>grid(n+2, vector<int>(m+2)); for (int i = 1; i <= n; i++){ for (int j = 1; j <= m ; j++){ cin >> x; if (x == '.') { grid[i][j] = 1; //add_adj(i,j); } if (x == 'A') { grid[i][j] = 1; start.first = i; start.second = j; } if (x == 'B') { grid[i][j] = 1; end.first = i; end.secon...
'; vector>dir = {{0, 1}, {0, -1}, {1,0}, {-1,0}}; q.push(start); while (!q.empty, [make_pair(-1,0)] = 'U'; vector>dir = {{0, 1}, {0, -1}, {1,0}, {-1,0}}; q.push

Full text and comments »

  • Vote: I like it
  • -3
  • Vote: I do not like it

84.
By vishwalization, history, 2 years ago, In English
DOUBT : getting SEGMENTATION fault ![ ](/predownloaded/c3/bf/c3bfa20ec5040650f8cca704bf60951f431bcdda.png) ~~~~~ Your code here... #include <bits/stdc++.h> using namespace std; #define ln '\n' typedef long long ll; typedef unsigned long long ull; typedef long double ld; string s; string cur_path; int net; map<char, int> mp; map<int, char> goes_through; // checks if the path goes through few dir given in string bool is_goes_through(){ for(auto x: goes_through){ if (cur_path[x.first] != x.second){ return 0; } } return 1; } int rec(int level){ // base case if (level == 48){ if (net == -6 && is_goes_through()){ return 1; } } int ans = 0; // recursive case for(auto x: mp){ cur_path.push_back(x.first); net += mp[x.first]; ans += rec(level + 1); cur_path.pop_back(); net -= mp[x.first]; } return ans; } void solve(){ cin>>s; mp['D'] = -1; mp['U'] = 1; mp['R'] = 2; mp['L'] = -2; for(int i=0; i< s.length(); i++){...
, int> mp; map goes_through; // checks if the path goes through few dir given in, // checks if the path goes through few dir given in string bool is_goes_through(){, for(auto x: goes_through) cout<<"idx = "<<<" dir = "<<

Full text and comments »

  • Vote: I like it
  • -14
  • Vote: I do not like it

85.
By at1, 16 years ago, In Russian
Мое мнение по поводу 60 раунда и оценка точности в C <h3>Контест</h3>&nbsp; Мне контест очень понравился, как отличная тренировка решения ботвистых задач. Мне не нравится, когда условие неполно, некорректно, неоднозначно. Здесь же все условия интуитивно понятные (мне) и, вроде, абсолютно корректные.<br> &nbsp; Также, по задачам подготовлены очень хорошие тесты (могу оценивать только то, что дорешал A-C).<br> &nbsp; Так что, к авторам вообще не может быть претензий, они подготовили оригинальный, качественный сет&nbsp; задач. Лично мне контест очень понравился, хоть и поверг мой рейтинг в пучины отчаяния =).<br> &nbsp; В каждой комнате все равны перед задачами и взломами, поэтому не вижу проблем с "неравенством" положений, о которых все пишут. Ну сразу же понятно, что в A всякие крайние случаи сыплются, а значит либо аккуратно на бумажке придумываешь решение, либо злостный тест, а лучше и то и другое. А дальше все покажет опыт, как и на других контестах.<br>[cut]<br> <h3>Разбор</h3>К сожалению, разбор задачи C мне, на...
точки с требуемой точностью 10-6, по формуле: a + dir * dist = a + ((b - a) / |b

Full text and comments »

  • Vote: I like it
  • +16
  • Vote: I do not like it

86.
By AL2BDIE95, history, 10 years ago, In English
Javadoc not working in windows command prompt << Solution Here >> **i just face same problem & take a lot of time to find the solution.** **i hope that " this topic help beginners like me " ;)** **just follow this steps to make JDK work correctly .** step no 1 : ----------- **right click on ( my computer ) &mdash; then choose properties.** ![ ](http://i68.tinypic.com/2vkfa0l.jpg) step no 2 : ----------- **choose advanced System settings** ![ ](http://i63.tinypic.com/alrl1s.jpg) Step no 3 : ----------- **left click on " Environment Variables..."** ![ ](http://i63.tinypic.com/2lsdu1s.jpg) Step no 4 : ----------- **1- left click on Path** **2- click on Edit** ![ ](http://i67.tinypic.com/j5cwvc.jpg) Step no 5: ---------- **get the dir. "see a pic."** ![ ](http://i68.tinypic.com/2cimqf.jpg) step no 6 : ----------- **left click on " New " then paste a dir that you copy it before** **Note : don't change any path that maybe cause a problem in ur OS .** ![ ](http://i64.tinypic.com/nqd1sp.jpg) Step...
**get the dir. "see a pic."**, **left click on " New " then paste a dir that you copy it before** **Note : don't change any path

Full text and comments »

  • Vote: I like it
  • -4
  • Vote: I do not like it

87.
By _H_A_W_K_S_, history, 3 years ago, In English
Error: non-aggregate type 'vector<int>' cannot be initialized with an initializer list Help me to fix this problem. ------------------ ~~~~~ #include<bits/stdc++.h> using namespace std; int main() { vector<int> dir = {1,2,3}; for (auto d : dir) { cout<<d<<endl; } return 0; } ~~~~~ Whenever I try to run this code in vscode I got this error => ![ ](/predownloaded/a3/ec/a3ecec00ada6980365748365a38a144c79c400e5.png) Is there anyone who ever faced this problem(in mac) and solved it. plz help me. It would be a great relief for me. Thanks in advance <3.
std; int main() { vector dir = {1,2,3}; for (auto d : dir) { cout<, int main() { vector dir = {1,2,3}; for (auto d : dir) { cout<<

Full text and comments »

  • Vote: I like it
  • +9
  • Vote: I do not like it

88.
By 0k-, history, 6 years ago, In English
nth lexicographical permutation of string/multiset? I'm curious about a hypothetical problem (I don't know if this appears anywhere): input is a string $s$ where $1 \leq |s| \leq 20$ and a number $n$ where $1 \leq n \leq |s|!$. Output the $nth$ lexicographical permutation of $s$. It is guaranteed that $n$ will not be larger than the total number of permutations of $s$. It's easy to solve this when each character in the string is unique (in general, a set). There's plenty of resources about how to generate the nth permutation of a set. Code snippets like [this one](https://github.com/SuprDewd/CompetitiveProgramming/blob/master/code/other/nth_permutation.cpp) that generate a permutation of the range $[0,n)$ that can be used as the indices for the original string, or the factorial/factoradic number system can be used as in [here](https://www.keithschwarz.com/interesting/code/?dir=factoradic-permutation). This doesn't work for all strings because it doesn't handle repeated characters. For example with finding the third lexicographic p...
/interesting/code/?dir=factoradic-permutation).

Full text and comments »

  • Vote: I like it
  • +24
  • Vote: I do not like it

89.
By zamazan4ik, 12 years ago, In Russian
Задача Лыжные гонки Доброго времени суток. Есть такая задача &mdash; Лыжные гонки. [Your text to link here...](http://informatics.mccme.ru/py-source/source/dir/16247) Во время лыжных соревнований N спортсменов стартуют с интервалом в 1 минуту. Скорость каждого лыжника на дистанции постоянна: i-й лыжник преодолевает 1 км за wi минут. Длина трассы равна L км. Считается, что i-й лыжник обогнал j-го (совершил обгон), если он стартовал позже j-го, а пришёл к финишу раньше него. Подсчитайте суммарное число совершённых во время гонки обгонов. Входные данные Первая строка входного файла содержит два целых числа N и L. Во второй строке через пробел расположены N целых чисел wi. 1<=N<=500000, 1<=L<=10^9, 1<=Wi<=10^9 Выходные данные Выведите единственное число &mdash; суммарное количество обгонов. Ограничение по времени &mdash; 2 сек Ограничение по памяти &mdash; 128\256 мб(не нашёл информации) Что я придумал по этой задаче : будем идти по порядку, увеличивая i. i лыжник обгонит j, если i>...
://informatics.mccme.ru/py-source/source/dir/16247)

Full text and comments »

  • Vote: I like it
  • +3
  • Vote: I do not like it

90.
By abhinav700, history, 4 years ago, In English
problem while declaring a 3d array i am doing a leetCode question which requires a 3d array for memorisation. i have followed every rule of using the ```memset``` function and creating the arrays still the array is not getting initialised with the value specified in memset function. I have been stuck on this from yesterday. Can someone pls help? Problem Link: https://leetcode.com/problems/knight-probability-in-chessboard/ CODE: ``` class Solution { public: int dir[8][2]={{-2,-1},{-2,1},{-1,-2},{-1,2},{2,-1},{2,1},{1,2},{1,-2}}; double solve(int n,int k,int r,int c,double dp[101][26][26]){ if(r<0 || r>=n || c<0 || c>=n) return 0; if(k==0) return 1.0; if(dp[k][r][c]!=2.0){ cout<<"k r,c : "<<k<<" "<<r<<" "<<c<<endl; cout<<"value : "<<dp[k][r][c]<<endl<<endl; return dp[k][r][c]; } double rate=0; for(int i=0;i<8;i++){ rate+=(solve(n,k-1,r+dir[i][0],c+...
/ CODE: ``` class Solution { public: int dir [8][2]={{-2,-1},{-2,1},{-1,-2},{-1,2},{2,-1, ; for(int i=0;i<8;i++){ rate+=(solve(n,k-1,r+dir[i][0],c+dir[i][1],dp)*0.125, class Solution { public: int dir [8][2]={{-2,-1},{-2,1},{-1,-2},{-1,2},{2,-1},{2,1},{1,2

Full text and comments »

  • Vote: I like it
  • +2
  • Vote: I do not like it

91.
By bkrtoni, history, 10 years ago, In English
using stdc++.h in visual studio We all know stdc++.h lib that includes all libs in c++ But we can't use it in visual studio so i know a way to use it in visual studio , and this may help any one using VS and want to use stdc++.h ### First thing Download stdc++.h lib this is a link to download the file [Download link](https://gist.github.com/eduarc/6022859) ### Second thing Copy the stdc++.h file Go to DIR C:\Program Files\Microsoft Visual Studio 12.0\VC\include\ Create new folder here and name it bits then paste stdc++.h inside the folder ### Last thing Open VS , make c++ project and try the Lib `#include<bits/stdc++.h>` and that is everything I hope that will help you :)
link](https://gist.github.com/eduarc/6022859) ### Second thing Copy the stdc++.h file Go toDIR C, ### Second thing Copy the stdc++.h file Go to DIR C:\Program Files\Microsoft Visual Studio 12.0

Full text and comments »

  • Vote: I like it
  • +20
  • Vote: I do not like it

92.
By Jeet_Karia, history, 7 years ago, In English
Scrapping Your Correct Submissions Now there is no need of saving each and every submission's source code you submit because a python script can do it for you and you just have to be relaxed. Note: It will scrap your latest submission to a problem in case of multiple submissions. Suppose the handle name is Jeet_Karia and directory where you want to save all your submissions is D:/Activities/Developer/Test <br> Sample Input: python scrap-cf-sub.py --handle Jeet_Karia --dir D:/Activities/Developer/Test And in some moments submissions will be in your directory. You can find the script [here](https://github.com/JeetKaria06/CF_Submissions/tree/master/Scrapping_Submissions) Sample Output in my case: ![ ](/predownloaded/3f/8e/3f8e8fad0216f142320f5301ab1f4c4b2c553f13.png)
D:/Activities/Developer/Test Sample Input: python scrap-cf-sub.py --handle Jeet_Karia --dir D, : python scrap-cf-sub.py --handle Jeet_Karia --dir D:/Activities/Developer/Test And in some

Full text and comments »

  • Vote: I like it
  • +23
  • Vote: I do not like it

93.
By Hepic_Antony_Skarlatos, history, 11 years ago, In English
Super Deal Game - Codeforces Api I wanted to use codeforces api for something and I came up with a game called 'super deal'. For any who doesnt know it,it is a game with bags. Each bag has its value(Here I use cf api. I take values from the rating of users. For example the highest you will see is for [user:tourist,2015-09-01] .), and you pick a bag,and after some other selection and negotiations you take the money of the bag you had last. Source is simple: "https://github.com/Hepic/Super-Deal-Cf-Style-" If someone is free and wants, he can contribute free. I would love that :) Also I uploaded here, for any who wants to see it: "http://zabidey.com/whateveridontcarelol/Super%20Deal(Cf%20Style)/index.html" (For windows because of ajax you need to open chrome writing in cmd: "start chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security"). If someone can improve it, go ahead. :) Thank you for your time !!!
-dir="C:/Chrome dev session" --disable-web-security"). If someone can improve it, go ahead. :)

Full text and comments »

94.
By mainnahihoo, history, 14 months ago, In English
Why i am getting TLE at this cses problem,need helppppppppppp this problem is minimal task [Link](https://cses.fi/problemset/task/3359/) can be solved by dp, i am using bfs or djikstra u can say , so i made a priority_queue and when first time when my string will be having the size of 2*n-1 means i had reached to end so this will be the answer lexicographically see the code i am getting TLE no wrong answer i think worst complexity will be O(N^2) ,Please help ~~~~~ struct cmp { bool operator()(const pair<pair<int,int>,string> &x, const pair<pair<int,int>,string> &y) const { return x.second > y.second ; } }; int check(int i,int j,int n){ return i>=0 && j>=0 && i<n && j<n; } string ans; vector<pair<int,int>>dir={{1,0},{0,1}}; string bfs(int i,int j,vector<vector<char>>&vec,vector<vector<int>>&vis,int n){ priority_queue<pair<pair<int,int>,string>,vector<pair<pair<int,int>,string>>,cmp>pq; string s; s+=vec[i][j]; pq.push({{i,j},s}); while(!pq.empty()){ auto it=pq.top()...
){ return i>=0 && j>=0 && i>dir={{1,0},{0,1, >>dir={{1,0},{0,1}}; string bfs(int i,int j,vector>&vec,vector>&vis,int n

Full text and comments »

  • Vote: I like it
  • -25
  • Vote: I do not like it

95.
By Nedy88, 16 years ago, In English
Codeforces Beta Round #26 (Codeforces format) Hello everybody,<br> <br> Codeforces Beta Round #26 will be held on Monday, the 16th of August, at 19:00 MSK. It will be <a href="http://codeforces.me/blog/entry/456">Codeforces format</a> round, and if all goes well it will be rated. Authors of the problems are <a href="http://codeforces.me/profile/RAD">Artem Rakhov</a> and me. Thanks to <a href="http://codeforces.me/profile/MikeMirzayanov">Mike Mirzayanov</a> and <a href="http://codeforces.me/profile/Nerevar">Dmitry Matov</a> for help in organizing it. <span dir="ltr" id=":3f">Also thanks to <a href="http://codeforces.me/profile/Julia">Julia Satushina</a> for translation of problems.</span><br> <br> Good luck, see you on the round!<br><br><i><p class="MsoNormal" style="font-style: normal;"><b>UPD:&nbsp;</b>The contest is over, thank you to everyone for participating.</p><ul style="font-style: normal;"><li><a href="http://codeforces.me/contest/26">Problems</a><br></li><li><a href="http://codeforces.me/contest/26/standings">...
href="http://codeforces.me/profile/Nerevar">Dmitry Matov for help in organizing it.dir, in organizing it. dir="ltr" id=":3f">Also thanks to , ">Дмитрию Матову за помощь в подготовке раунда. dir="ltr" id=":70">Так же спасибо, ://codeforces.ru/profile/Nerevar">Дмитрию Матову за помощь в подготовке раунда. dir="ltr" id=":70">Так

Full text and comments »

  • Vote: I like it
  • +35
  • Vote: I do not like it

96.
By wuovdj769, 14 years ago, In English
Flash Player Plugin for Ubuntu 12.04 Hi everybody.<br/> I'm having problem with installing <font color="#fff" style="background:#a00;padding:2px;">Flash Player</font> from Software Center. Downloaded <code class="tt">tar.gz</code> file. Don't know what to do next. Can anyone help ? Thanks everybody. :) <h1><font color="#a00">Summary</font></h1> Here are two ways to install <font color="#fff" style="background:#a00;padding:2px;">Flash Player</font> from <code class="tt">tar.gz</code> file.<br/> <h2>1. Manual</h2> <ul style="list-style:decimal;line-height:30px;"> <li>Extract <code class="tt">tar.gz</code> file.</li> <li>Copy <code class="tt">libflashplayer.so</code> to appropriate Plugins folder. (ex: for <font color="#fff" style="background:rgb(221, 72, 20);padding:2px;">Mr. Firefox</font> :) plugins folder is <code class="tt">/usr/lib/mozilla/plugins/</code>)</div></li> </ul> <h2>2. Using Terminal (Recommended)</h2> <ul style="list-style:decimal;line-height:30px;"> <li>Open terminal (shortcut: <code clas...
archive is (using cd(change dir) ). * Extract archive. Use , (change dir) ). * Extract archive. Use tar xvf <archivename>

Full text and comments »

  • Vote: I like it
  • -3
  • Vote: I do not like it

97.
By pin3da, history, 11 years ago, In English
Notebook generator. Today I wrote a program to auto-generate team notebooks based on the source code. The program is available [here](https://github.com/pin3da/notebook-generator). You can install it from npm doing ~~~~~ npm install -g notebook-generator ~~~~~ Basically I use nodejs to iterate over the dirs/files in order to create a .tex file and then generate a pdf using pdflatex. I hope that could be useful.

Full text and comments »

  • Vote: I like it
  • +19
  • Vote: I do not like it

98.
By Singledigit, history, 10 years ago, In English
Runtime Error Test 1: Tree Construction Hello, I have no idea how this is failing. It works perfectly fine from my terminal. I am currently having a runtime error on Tree construction: http://codeforces.me/problemset/problem/675/D g++ --version Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 7.3.0 (clang-703.0.29) Target: x86_64-apple-darwin15.4.0 Thread model: posix InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin Error: Test: #1, time: 0 ms., memory: 2000 KB, exit code: -1073741819, checker exit code: 0, verdict: RUNTIME_ERROR Checker: _null_ Here are all my latest submissions: http://codeforces.me/submissions/Singledigit Code ~~~~~ /* CodeForces Problem 675D * http://codeforces.me/problemset/problem/675/D * Objective: Create BST and Print out Parent nodes */ #include <vector> #include <iostream> using namespace std; class tree{ pu...
-include-dir=/usr/include/c++/4.2.1 Apple LLVM version 7.3.0 (clang-703.0.29) Target: x86_64-apple

Full text and comments »

  • Vote: I like it
  • +5
  • Vote: I do not like it