2-D Permutations

View as PDF

Submit solution

Points: 10 (partial)
Time limit: 2.0s
Memory limit: 1G

Problem type
Allowed languages
Ada, Assembly, Awk, Brain****, C, C#, C++, COBOL, CommonLisp, D, Dart, F#, Forth, Fortran, Go, Groovy, Haskell, Intercal, Java, JS, Kotlin, Lisp, Lua, Nim, ObjC, OCaml, Octave, Pascal, Perl, PHP, Pike, Prolog, Python, Racket, Ruby, Rust, Scala, Scheme, Sed, Swift, TCL, Text, Turing, VB, Zig

Edward spent the whole weekend brainstorming problems involving 2-D arrays. Unfortunately they were all too hard, so he came up with this instead:

You are given N \times M integers, numbered from 1 to N \times M. You would like to arrange these numbers into an N \times M array A. The rows are numbered from 1 to N and the columns from 1 to M. Denote the number assigned to the ith cell from the top and the jth cell from the left A_{i, j}. Call an arrangement valid if for all cells with i > 1, A_{i, j} > A_{i - 1, j}, and for all cells with j > 1, A_{i, j} > A_{i, j - 1}. You are also given Q queries. For each query a number q_i is given, and you must return the number of different cells q_i can be placed in all valid arrangements.

Edward has no idea how to solve this problem either. Please help him solve it.

Input Specification

The first line will contain three integers N, M, and Q, the dimensions of the array and the number of queries.

The next Q lines will each contain one integer q_i, as specified in the problem statement.

Output Specification

Output Q lines, the ith line containing the number of different cells q_i can be placed in all valid arrangements.


For all subtasks,

1 \le N, M \le 5000

1 \le Q \le 10^6

1 \le q_i \le N \times M

Subtask 1 [15%]

1 \le N \times M \le 10

1 \le Q \le 10

Subtask 2 [35%]

1 \le N, M, Q \le 300

Subtask 3 [50%]

No further constraints.

Sample Input 1

2 2 4

Sample Output 1


Explanation for Sample 1

The two valid arrangements are:


2 and 3 can be placed in two different cells, while 1 and 4 can only be placed in one.

Sample Input 2

1 3 3

Sample Output 2


Explanation for Sample 2

The only valid arrangement is:


Since there is only 1 valid arrangement, each number can only be placed in 1 unique cell.

Sample Input 3

5 5 1

Sample Output 3


Explanation for Sample 3

The following diagram shows the 11 possible cells 18 can be placed in. Green cells denote possible cells, while red cells denote otherwise:


  • 0
    Overseas  commented on Dec. 31, 2020, 4:49 a.m. edited

    i am certain that python is not being able to handle this, got all the answer correct but always TLE for part 3.

    edit; it can, but only with pypy3 or pypy2

  • 1
    andrewtam  commented on Aug. 14, 2020, 11:57 a.m.

    Are all queries distinct?

    • 1
      pblpbl  commented on Aug. 14, 2020, 12:35 p.m.

      Not necessarily.