題目的難度顏色使用 Luogu 上的分級,由簡單到困難分別為 🔴🟠🟡🟢🔵🟣⚫。

🔗 🟠 P14358 [CSP-J 2025] 座位

Problem Statement

題目簡述

考場共有 n×mn \times m 名考生,每位考生的第一輪成績皆不相同。所有考生將按照成績由高到低,以蛇形分配的方式安排在 nn 個 row 與 mm 個 column 的座位中。

具體蛇形分配規則如下:

  • 成績第 11 高到第 nn 高的考生,依序安排在第 11 個 column 的第 11 個 row 到第 nn 個 row。
  • 成績第 n+1n+1 高到第 2n2n 高的考生,依序安排在第 22 個 column 的第 nn 個 row 到第 11 個 row(即 row 號反向)。
  • 成績第 2n+12n+1 高到第 3n3n 高的考生,依序安排在第 33 個 column 的第 11 個 row 到第 nn 個 row。
  • 依此類推。

給定考場的 row 數 nn 與 column 數 mm,以及所有考生的成績 a1,a2,,an×ma_1, a_2, \dots, a_{n \times m}(其中 a1a_1 為目標考生小 R 的成績),求小 R 的座位在第幾個 column 與第幾個 row。

Constraints

約束條件

  • 1n,m101 \leq n, m \leq 10
  • 1ai1001 \leq a_i \leq 100
  • 所有 aia_i 互不相同

思路:模擬與週期性映射

將所有成績由高到低排序後,目標考生在排序序列中的索引(從 00 開始)即代表其排名。

考場座位按 column 填充,每個 column 容納 nn 個座位。將一維索引 ii 拆成二維:

  • c=i/nc = \lfloor i / n \rfloor(column,從 00 開始)
  • r=imodnr = i \bmod n(row,從 00 開始)

座位的蛇形規則:偶數 column(cc 為偶數)由上到下填充,row 即為 rr;奇數 column 由下到上填充,row 需反轉為 n1rn - 1 - r。最後將 c,rc, r 分別 +1+1 即得答案。

蛇形填充的通用公式

按 column 蛇形填充、row 數為 nn 時,一維索引 i(c,r)i \mapsto (c, r)

  • c=i/nc = \lfloor i / n \rfloor
  • r={imodnc 為偶數n1(imodn)c 為奇數r = \begin{cases} i \bmod n & c \text{ 為偶數} \\ n - 1 - (i \bmod n) & c \text{ 為奇數} \end{cases}

c & 1 判斷奇偶並反轉 row,是蛇形矩陣 / S 型曲線的通用技巧。

複雜度分析

  • 時間複雜度:O(nmlog(nm))\mathcal{O}(n m \log(n m))(瓶頸在排序)
  • 空間複雜度:O(nm)\mathcal{O}(n m)(儲存成績陣列)

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
def solve():
n, m = map(int, input().split())
A = list(map(int, input().split()))

x = A[0]
A.sort(reverse=True)
i = A.index(x)
c, r = divmod(i, n)
if c & 1:
r = n - 1 - r
print(c + 1, r + 1)


if __name__ == "__main__":
solve()

寫在最後

Cover Image Credit

The cover image was created by @4AUB. All rights belong to the original artist.

It is used here only as a non-commercial cover illustration for this note. I do not claim ownership of the artwork.

If you are the copyright holder and believe this usage is inappropriate, please contact me by email or leave a comment. I will remove the image promptly.