We will hold AtCoder Beginner Contest 165.

- Contest URL: https://atcoder.jp/contests/abc165
- Start Time: http://www.timeanddate.com/worldclock/fixedtime.html?iso=20200502T2100&p1=248
- Duration: 100 minutes
- Number of Tasks: 6
- Writer: beet, DEGwer, kort0n, sheyasutaka, smeke, ynymxiaolongbao
- Rated range: ~ 1999

The point values will be 100-200-300-400-500-600.

We are looking forward to your participation!

UPD:

In Problem E, the constraints says N <= 100000, but it turned out that the inputs are made under the condition N <= 200000.

It was revealed that only 6 people were affected by the defect of the problem E constraint, and 4 among them were rated competitors. As the impact is very minor, contestants excluding the four are going be rated, and the affected four will also be rated after rejudging to get AC on their submissions.

2 ABC this weekend, what a time to be alive! Thanks a lot AtCoder team for making this quarantine more fun!

I guess extra contests are to cover up for the unrated ones

Did the start time just got extended by 5 minutes?

Yep

5 more minutes! extended by 10 now... Seems like they're having some issues.

as always !

website crashed ?

Delayed by 10 minutes.

I am getting signed out repeatedly

site is not loading?

RIP

Site down?

Again 502 Bad Gateway :(

It's up now

504 Gateway Time-out:(

Postponed for 5 minutes.

Now ten minutes.

Start time extended by 10 minutes.

Its good that they acted quickly otherwise this contest also could be unrated :D

Looks like the start time is extended by 10 minutes.

extended by more 5 min :(

10 mins.

website is loading too slow

Will they just postpone the contest by increments of 5 minutes until enough people go away and there is less load on their servers??

delayed due to inadequacy in problem

“The start will be delayed for 10 minutes due to an inadequacy discovered in the problem. I'm sorry.“

Here we go

C is too hard for C, imo.

easy

yeah, for me it was hard :(

Same for me. That C was insane :(.

Solved E, but didn't C...

I solved C but couldn't solve E :(

10! algorithm would work

take a look at the constraints

it would be (n+m-1)C(m-1), so worst case 19C10

How could you get this formula?I saw same question in one educational round but i don't know proof behind this formula?

there's a n*m size rectangle, at the beginning, you are at the bottom-left corner, now that formula is the number of ways to get to the right side of the rectangle only go right or top.

You have M distinct numbers you can give each number some frequency and frequency of each number can be between [0, N] (N = length of sequence), since you have to make sequence increasing so for any fix combination of numbers and frequencies there will be only one increasing sequence. So now the problem is reduced to find the number of solutions of equation f1+f2+f3+..+fm = N, where fi is frequency of ith number in the sequence.

total sequences are 92378 in worst case. C(19,10)=92378

Solved F but not C and E.

same. F was easy, if you know O(nlogn) solution for finding LIS.

Well actually I was doing LIS in O(nlogn) and I got TLE on 6 tests :C

I tried solving F using coordinate compression and range-max segment tree. But i kept getting WA :( . Been trying to figure out the error, but I wasn't able to. Here is my submission WA solution

It also happened to me.

lets denote some variable: max_val=maximum compressed value

prev_val=query(pos[u],pos[u])[value of the index of pos[u] , before line 45]

1) in line 45:

update(pos[u], val) -> update(pos[u],max(val,prev_val))

2) in line 46:

ans[u] = val -> ans[u] = query(0,max_val)

3) in line 52:

update(pos[u], 0) -> update(pos[u],prev_val)

I suppose this works fine...

Thanks a lot. Realized that for considering the LIS for a path from 1 to k, I take the answer as dp(k), instead of max(dp(i)) for i from 1 to k.

+1. Solved rest but couldnt do this.

It was too hard for me too. I thought number of combinations will be too large. But turns out there can be at max 92378 for n=10 and m=10. So brute force works.

How to solve C !

just try all the state.

Though I doubted whether it will get TLE in the beginning...

How does this work, I came to the conclusion that there are $$$10^{10}/2$$$ possible arrays to check. To much.

No you are wrong ,There are much fewer arrays!! You can write a dfs to count them.

There are 92378 possible arrays for N = 10, M = 10 that have A[i]>=A[i-1] only.

Well, thanks for explanation.

how did you got this ?

Either go with a brute solution and find using code or use P&C and we can say sum of gaps between consecutive numbers is at max m-1 and number of gaps are n-1, so g1+g2+g3... gn-1 + k = m-1, so number of whole number solutions of this equation are m-1+n-1Cn-1

actually the number of array is 10 choose 10 with repetition so that means it is 19 choose 10 which is equal to 92378. I have solved it in the most crazy way. my submission

I did'nt get it... how is it becoming 19C10?

It is a well known concept called combination with replacement. Imagine you have a pool of numbers from $$$1 - 10$$$, and you want to select $$$10$$$ numbers with replacement (ex you can take the same number multiple times) this can be found using $$$n+k-1 \choose k$$$. If you want to read more about [here](https://en.m.wikipedia.org/wiki/Stars_and_bars_(combinatorics))

Correction: it is $$$n + k - 1 \choose n$$$ which equal to $$$n + k - 1 \choose k - 1$$$

262 line code! really u r a coder.

we should only consider monotonically increasing sequence

Combinatorial way to look at it.

You need to find number of arrays $$$A = \{ A_1, A_2, ..., A_N \} $$$, such that $$$ 1 \le A_1 \le A_2 \le ... \le A_N \le M $$$.

Let $$$ x_i $$$ be the number of occurences of $$$ i $$$ in the array. Then we require number of solutions to $$$ x_1 + x_2 + ... + x_M = N $$$, where $$$ x_i \ge 0 $$$.

This, given by Stars and Bars, is simply $$$ {N+M-1} \choose {M-1} $$$ = $$$ {10+10-1} \choose {10-1} $$$ = $$$ 19 \choose 9 $$$ = $$$92378$$$.

I usually use this website to do quick calculations for combinations, during contests.

:)

Backtracking

would you plese explain!

Look at my code you'll get it: https://atcoder.jp/contests/abc165/submissions/12619964

basically we generated all possible arrays.

just

int k = v[cur — 1]; while (k<= m) { v.push_back(k); dfs(cur + 1); v.erase(v.begin() + cur); ++k; }

You can write a recursive brute force, which will include all possible states we can go to.

Consider we want to fill n places. We start from place_id = 1, and num = 1.

Now we have 3 possible cases:

If you are confused, you can take a look at my submission, though it isn't the cleanest. Submission

I hope it helped.

Honestly, I think it is not very wise to give such C and D in abc contest.

I am sure there a thousends(?) of possible participants not submitting any solution because scared by a hard C and a D full of corner cases.

Dont get me wrong, I think these are nice problems, but simply misplaced.

I can solve D by math with no corner cases. https://atcoder.jp/contests/abc165/submissions/12609383 Can not solve C. E. F.

D was just to take x as min(b-1,n).

F was easy with segment tree i think

Are you serious ?Why you used segment tree for E?

sorry my bad, F

I think F by set will be more easy

check thatvector < int > v[200005];

int a[200005],ans[200005];

bool vis[200005];

set < int > s;

void dfs (int r )

{

}

Would you please simulate your math formula!

Take x as min(b-1,n)

The second part of the function becomes zero and the first part becomes maximum.

you need to maximize, but if you observe for any x >= b, float[x/b] will always be greater than 0, and then you multiply it with A, but float[Ax/b] can atmost be equal to that. Thus its always optimal to make float[x/b] = 0, so that you answer is float[Ax/b]. To make that equal to 0, just take max x < b, but since x <= N, x = min(n, b-1). Then return the answer.

can you explain your solution please?

Explanation for D; If x increased by B, value not change, so we only consider x in range 0 — min(b-1,n); So The second part of the function becomes zero and the first part becomes maximum.

Is C very hard?just try all the state!

I thought about that, just can not believe it will not get TLE. Maybe I evaluate time complexity wrong.

Why not write a simple dfs to count the number of them?

I calculated Combination(20, 10), and ... What the fxxx was I thinking about!!!

Is it $$$C_{m+n-1}^n$$$ ?

Yes, you are right. I do not know how to input formula.

The English Commentary for Problem C and D is here

D with binary search... Wait. what? How? What does your check function do? The function isn't strictly increasing nor decreasing as far as I understand..

it's not increasing nor decreasing... however if you notice function is increasing in intervals of b. eg. from x = 0,1,2,..b — 1 f(x) is increasing at x = b f(x) again drops and starts increasing same as for previous x

Exactly, since it drops at B, you can't binary search on interval (0,n). If you are Bsearching on interval (0,B-1), that isn't required, since it is increasing from 0 to B-1...so B-1 is going to give you maximum.

Also, I am not sure if this Bsearch on (O,N) will work always. Since it is repeating maybe that is why it worked.

Please provide proof of your construction in D

The best idea is to use min(b-1,n). Simple and cute!

Can someone give a hint on E and F?

For F, Use Cute LIS :P to find lis for every node in dfs. My Submission.

Why is my ternary search failing on one test case for D? :((

https://atcoder.jp/contests/abc165/submissions/12647186

Why you are using ternary search ... Its just simple math

F

I just assumed the function was unimodal and tried ternary search and it almost AC'd. Can you elaborate your solution?

EDIT: unimodal not monotonic

The function is repeating after every B values of X.

Try to express X = qB + r and solve the equation. You will find that, function is max when r = (B-1). Also, in case, b — 1 > N, then N is your answer cause, from 0 to B-1 the answer is increasing.

when did you meet mike mirzayanov?

@chosun Notice that if n>b no binary search or ternary search if you apply binary search from 1 to n. Binary search's lower and higher bounds will be [1, min(n, b)]

It works now thanks. Damn I was pulling my hair out last 5 minutes trying to debug this thing!

This simple mistake cost 4 wrong submissions to me :(

No need for ternary search, answer is monotonic with modulo value with B.

When you know it is monotonic between 0 to B-1, when not just return B-1...

or binary search My submission

Anyone tell how to do C

C is just backtracking. Try all possibilities of the sequence

Problem statement of C was so confusing.Can anyone explain it?

Please look at English Commentary of problem C here Thank you! Hope that helps!

You are asked to create an array a, of size N. You should place values in that array from 1 up to M. The array should be not decreasing.

Then you get those quadrupels. If you put at position a and b values, so that the difference is c, you get d points.

Try to find an array with maximum possible points.

I`m soooo stupid.

How to solve F ?

Apply the O(nlogn) algorithm for LIS during the dfs while nullifying the changes made by a particular branch of a node when we visit its another branch.

I maintained a segment tree for current root to node path for lis, and as i move down i make updates like in normal lis, and as i move up, i roll-back on the changes i did previously.

With segment trees and coordinate compression was required I think to backtrack.

All the people complaining about C being too hard. Is it possible that they didn't notice the constraints that array is in increasing order

`A[1] <= A[2] <= A[3]..... <= A[N]`

? Because I skipped it initially and thought for several minutes that total case are $$$10^{10}$$$ which was outside the time limit.Same happened with me. How many possible combinations are possible ?

a1 <= a2 <= ... <= an , (1<=ai<=m)

Solved it, but I couldn't prove the time complexity.

Observe, that if you pick set of numbers, there can be only one possible array, so you just need to count number to choose n elements from 1 to m, it is exactly $$$\binom{n+m-1}{n}\le 92378$$$

There is a small mistake. I think the time complexity should be $$$C_{n+m-1}^{m-1}$$$.

It's actually the same because $$$\binom{n}{k}=\binom{n}{n-k}$$$

I'm sorry. It's my mistake. I didn’t think twice. So stupid.

And... is 10^10 not outside the time limit?

First i wrote a dp solution to count how many such arrays exists. Then used brute force.

SpoilerIn fact there are only $$$C_{m+n-1}^n$$$

how to implement problem B ?? can anyone post their accepted solution

https://atcoder.jp/contests/abc165/submissions/12599633

Brute Forces worked fine in given time limit. https://atcoder.jp/contests/abc165/submissions/12598199

Problem B

Solns/Approaches

A. Check every element

B. Observe that answer never exceeds 5000 (use log to check). We can loop until success.

C. Generate every possible combination. In python, we have

`combinations_with_replacement`

which generates exactly what we needD. Observe that for $$$x < b$$$, $$$\lfloor x/b \rfloor$$$ is zero. We want to take $$$x = kb-1$$$. Also observe that taking $$$k > 1$$$ always make the answer worst. We take $$$x$$$ as $$$\min(n, b-1)$$$.

E. What we need is set of $$$(a, b)$$$s such that distance between $$$a, b$$$ never occurs twice. (Considering not only b-a, but we have to consider the other way. e.g, when $$$n = 10$$$, distance between $$$1$$$ and $$$10$$$ is 1 and 9. both should not appear again.)

When $$$n$$$ is odd, take $$$(1, n), (2, n-1), \dots$$$. One can easily show that this is valid.

When $$$n$$$ is even, take those values until we can't. (e.g, when $$$n = 10$$$, we take $$$(1, 10)$$$, $$$(2, 9)$$$ but not $$$(3, 8)$$$ since distance between $$$(3, 8)$$$ is 5 and 5 — repeated.) Then, discard one unused value and proceed. (e.g, after two takes, use $$$(3, 7)$$$ instead of $$$(3, 8)$$$, and $$$(4, 6)$$$.

Submission : https://atcoder.jp/contests/abc165/submissions/12617571

F. Consider computing LIS length in $$$O(n \log n)$$$ time with DP and

`lower_bound`

. (without considering the actual values). When we do this, we discard what was in that spot (lower bound). Instead of doing this, keep those values by`multiset`

or stuff like that. We traverse tree in DFS order, pushing values we meet in LIS-solving pattern but keeping values instead of throwing away. When we traversed all of it's subtrees, we erase value of the node from where we pushed. To do this we track the number of non-empty multisets and index we pushed each value in. Time complexity $$$O(n \log n)$$$.Submission : https://atcoder.jp/contests/abc165/submissions/12637543

@gratus907 can you please tell how you came to conclusion for problem E?

I thought it intuitively after some casework... and I tried to prove my thought (I mean, not rigorously, but like convincing enough to start writing code)

As I've wrote, a case when two people meet twice is only when there exists $$$(a, b)$$$ and $$$(c, d)$$$ which $$$b-a$$$, $$$n+a-b$$$, $$$d-c$$$, $$$n+c-d$$$ has repetitions. Try some casework in $$$n = 8$$$, $$$n = 10$$$ to convince yourself with this statement :)

I actually have nothing much to say as I did tons of caseworks on paper...:(

Thanks.

You don't really need any multiset for problem F. Just change the value at lower_bound and remember what it was. After solving all subtrees and updating the answer just return the value to what it was. Submission

Apparently yes.. I discussed this problem with my friend after the contest and he also said the same thing. I felt very dumb since he coded like 800 bytes while I coded more than 2000... lol

I have no idea how I managed to think returning values by dfs tree and then thought something like "WOW I want

`vector<multiset<int>>`

" and started coding :(How to solve D?

take x as min(b-1,n)

The target is to keep the minus part as small as possible.So tried to make the second part 0. So if n>=b, made it x=b-1 and it worked fine.

The Editorial is in Japanese. I want an English editorial.

Generally they used to post english editorial after 5-6 days,but if you want you can google translate the pdf.(After translation it will have weird english but understandable)

I'm assuming some greedy strategy works for C. Can somebody please post their logic/solution? I filtered queries such that for each (a, b) indices pair — the optimal c for maximum d is known. For the array A[n], I set A[0] = 1. From here, I am confused about how to construct the rest of the array. I tried a couple of ways but there were always some cases not adhering to the rule.

C was a pruned brute solution i think.

Yeah. During the contest, I thought the time complexity would be too much. I wish I had checked it with a program though. For n = m = 10, there are about 48,000 possible sequences only.

Spoilerimport java.util.*; import java.io.*; class Main { static int min; static int count(int[] a, int[][] queries) { int ans = 0; for(int[] q: queries) { if(a[q[1]]-a[q[0]]==q[2]) ans+=q[3]; } return ans; } static void recurse(int[] a, int idx, int prev, int m, int[][] queries) { if(idx==a.length) { min = Math.max(min, count(a, queries)); return; } for(int i = prev; i<=m; i++) { a[idx] = i; recurse(a, idx+1, i, m, queries); } } public static void main (String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int m = sc.nextInt(); int q = sc.nextInt(); int[][] queries = new int[q][]; for(int i = 0; i<q; i++) queries[i] = new int[]{sc.nextInt()-1, sc.nextInt()-1, sc.nextInt(), sc.nextInt()}; int[] a = new int[n]; min = Integer.MIN_VALUE; recurse(a, 0, 1, m, queries); System.out.println(min); } }

It seems difficult orz

I think E is harder than F, as I'm not good at construction and pattern observing

F was like if you know segment tree you will solve it immediately. Nothing special was in it

How is segment tree related to F? I think most contestants solve it like this: submission

You can find lenghh of LIS ending at a node u, using segment tree as well after compressing a[i] s

Oh, I got it. But I think this implementation is much easier.

Could you please Explain, how to solve F using segment tree. Thanks It_Wasnt_Me

Is this round a bit easier than before? I used to solve 4 or 5 problems but today I solved 6 within a short time. Well anyway the problems are still very good (like, you can solve D and E with about 300 bytes of code but you need to think a long while). BTW, I think C is a bit hard for C. Since DFS may be not very "beginner-friendly".

D one was way too easier than the C one

Check Same question ... I still missed it.. hard luck today.

F is an easier version of NA Southeast Regional 2019 problem G

Here it is on Kattis: https://open.kattis.com/problems/neverjumpdown

谁知道结果什么时候出来啊（When rating changes?）（I can't speak English well……）

Nice contest!

This comment shouldn't be answered. This is a problem from an ongoing contest, Bubblecup.

From stars and bars trick we get for C only 92378 states are there i.e ncr(10+10-1,10-1)

A. Oh, constraints are really small, let's just iterate.

B. Hm, it's exponential growth, I think max answer is not too big. Let's write and see (turns out max answer was in samples, but I didn't notice).

C. Hm, seems like a lot of states, no idea, let's read D.

D. Hmm, let's write bruteforce and see. Oh, it's always zero for multiples, ok, let's take multiple-1 if we can.

C. Hmm, maybe there are not too many states? Let's write bruteforce and see. Oh, it's really small, dumb me. (It's just C(n + m — 1, n))

E and F are nice, but quite easy.

How do you arrive at C(n + m — 1, n)? I had to count them by writing the dfs.

https://codeforces.com/blog/entry/76792#comment-614207

The sum of gaps between consecutive numbers is less than equal to m-1, it's basic P&C afterwards.

Watch this: https://youtu.be/XcmHB8nrlJE?t=722

This is a classic stars and bars application.

Note the condition that $$$1 \leq A_1 \leq A_2 \leq ... \leq A_n \leq M$$$. Thus, it is sufficient to count how many times each number from $$$1$$$ to $$$M$$$ appears in the sequence (because we would then only have one way to arrange these numbers---in nondecreasing order). So, now imagine a line with $$$N$$$ stars and $$$M-1$$$ bars. The stars before the 1st bar corresponds to the number of 1s, the stars between the 1st and 2nd bar correspond to the number of 2s, etc. For example, if m=4 and n=7, then

`*||****|**`

corresponds to one $$$1$$$, zero $$$2$$$s, four $$$3$$$s, and two $$$4$$$s. So, how many possible ways are there to arrange $$$M-1$$$ bars and $$$N$$$ stars in a line? There are $$$M+N-1$$$ "spaces", and of them we need to choose $$$N$$$ locations to be where we place the stars. We place the bars in all other locations.Thanks!

Isn't it "N locations to be where we place the

stars. We place thebarsin all other places"?You are correct, I have edited it now. Thanks

Can someone explain the observation made in problem E.

check thiscould be helpful but a bit long explanation

Thanks.. Quite good explanation

in problem E: if i match 1 with n then 2 with n-1 and so on (m times) why is it wrong

I got WA with this approach in 9 test cases

For

`8 3`

, you would matchConsider, initially, $$$A = 1$$$, $$$B = 3$$$. They will fight at rounds 3($$$A = 3$$$ and $$$B = 6$$$) and 7($$$A = 7$$$ and $$$B = 2$$$).

This strategy works for odd N though.

But this only happens when they have the same distance between the pairs. So if you avoid that special case, should it be right? https://atcoder.jp/contests/abc165/submissions/12657318

For

`8 3`

your code prints exactly the same output of my previous message.initially,B = 4

In your reply,B=4

Can anyone prove the running time complexity for the brute solution of C please?

O(Q * 92378) because number of valid(non-decreasing arrays) arrays with n = 10 and m = 10 are 92378. You can calculate this with dp or with Combinatorics.

Code for Counting with DpAuto comment: topic has been updated by chokudai (previous revision, new revision, compare).May someone help me debug F: LIS on Tree? I have done using binary search and dynamic programming. I have used 0-indexed dp. My submission: https://atcoder.jp/contests/abc165/submissions/12674946

testans[v] will not be lo + 1. It will be the current size of vector. Just changed that got AC: https://atcoder.jp/contests/abc165/submissions/12675337

Sorry my bad. I thought the length of LIS at node v. Thanks a lot for your help.

hello?

How does the checker work in E? chokudai

For all the pairs given by the user check their difference both ways. Like 1 and 10 will have difference 1 and 9. These differences should be all different. So you can check in O(M).

I can't understand why my A solution fails Here's my code

k=int(input()) a,b=map(int,input().split()) if b-a+1>=k: print('OK') else: print('NG')

can anyone point out my mistake

`a=b=k`

thanks.i misunderstood the question

why would I get WA for problem.E

I found bug!

I believe the test files for the problem E were incorrect.

Instead of

n <= 100000, it should bem <= 100000. If I write an assert statement for the value of n being less than or equal to 1e5, the verdict is RE, while for 2e5+2 it is AC.Oh, there was a clarification as well, my bad. :(

Problem F:I have used LIS(nlogn) with B.F.S. but getting T.L.E......please help. https://atcoder.jp/contests/abc165/submissions/12695808

You may try dfs instead.(Read my code for more info).

I have used dfs but got TLE Here is the link: https://atcoder.jp/contests/abc165/submissions/12791770

You shouldn't pass a "vector L" in a function.You know,vectors are like arrays,so they require time to pass between functions.Try changing it to" vector &L",which passes a "virtual" vector(like a pointer).That shall get an AC.

Or you can make L an array out of the dfs functions.My code used just that.

Ok thanks. But can you figure out complexity of that code

O(n log n) for dp,plus a constant(of the vector).It's good enough.

Sorry for my code?

Can you figure out the complexity of my above code?

O(n^2)(for passing the vector).

Thank you I got the concept. Whenever we pass a vector by value it copies the content rather than updating it which is costly

Here is my list of submissions.You can use that as reference.

Why are there different results when using GCC and Clang? There are 4 testcases that fail to pass, but my method has no problem. So I checked the official testcase and the input and output, and found that the final problem is that GCC and Clang have different results. I want to know why? ? ? ! ! ! here is my two submission:(the first is AC and the second is WA,but the code is exactly the same!) Your text to link here... Your text to link here...

Wangxuelong, the defined arrays a,b,c,d should have length 51 if you intend to write into them at positions 1, ..., 50 — this causes your code to write outside of bounds of the arrays, causing undefined behavior (it can still theoretically work, but also the compilers decided to zero out all variables in your program, it would still be a valid thing to do according to C++ spec — the compiler is free to do anything it wants when you do out of bounds access).

Thank you very much!

For E detail explanation with examples and code check here

Can someone suggest similar problems to C?

search for backtracking problems

Can anybody find me the bug with this solution for problem C? Since both n and m is very small, I literally checked all possible combinations of the first m numbers using bit masking, but for some weird reasons, the combinations are not being properly generated, please help me in finding the potential bug in this submission.

For E，can some one tell me why this is wrong: void solve() { cin>>n>>m; int now=1; for(int i=1;i<=m;i++) { cout<<now<<" "<<(n+now-i-1)%n+1<<endl; a[now]=1; a[(n+now-i-1)%n+1]=1; while(a[now])now=(n+now-1-1)%n+1; } return ; }

My bad,I find the bug