QOJ.ac

QOJ

حد الوقت: 1 s حد الذاكرة: 2048 MB مجموع النقاط: 100 الصعوبة: [عرض] قابلة للهجوم ✓

#18202. DFS 序 6

الإحصائيات

Little Cyan Fish 熱愛 DFS 序。今天他再次研究這個主題,但這次是在無向簡單圖而非有根樹上進行。

給定一個包含 $n$ 個頂點(標號為 $1$ 到 $n$)的連通無向簡單圖 $G$ 以及一個起始頂點 $s$。從 $s$ 開始的 $G$ 的 DFS 序是透過下方所示的深度優先搜尋所造訪頂點的順序;若有多個選擇,則總是優先造訪標號最小的未造訪鄰居,因此 DFS 序是唯一的。

演算法 1 本題使用的 DFS 序

 1: procedure DFS(vertex x)
 2:     Mark x as visited
 3:     Append x to the end of dfs_order
 4:     for each vertex y adjacent to x in G, in ascending order of label do
 5:         if y is not yet visited then
 6:             DFS(y)
 7:         end if
 8:     end for
 9: end procedure
10:
11: procedure GENERATE(G, vertex s)
12:     Mark all vertices as unvisited
13:     Let dfs_order be an empty list
14:     DFS(s)
15:     return dfs_order
16: end procedure
problem_18202_1.png

一個包含 7 個頂點與 7 條邊的圖。從頂點 1 開始的 DFS 序為 [1, 2, 3, 7, 4, 5, 6]。

Little Cyan Fish 準備了 $n$ 個 $1$ 到 $n$ 的排列 $a_1, a_2, \dots, a_n$。每個 $a_i = [a_{i,1}, a_{i,2}, \dots, a_{i,n}]$ 都是他聲稱從頂點 $i$ 開始的 DFS 序。

請重建任何一個頂點為 $1, 2, \dots, n$ 的連通無向簡單圖 $G$,使得從每個起始頂點 $i$ 開始的 DFS 序皆等於 $a_i$,或者判斷不存在這樣的圖。

輸入格式

輸入包含多筆測試資料。第一行包含一個整數 $T$ ($1 \le T$),代表測試資料的數量。

對於每筆測試資料,第一行包含一個整數 $n$ ($1 \le n \le 200$)。接下來的 $n$ 行,每行包含 $n$ 個整數;第 $i$ 行包含 $a_{i,1}, a_{i,2}, \dots, a_{i,n}$ ($1 \le a_{i,j} \le n$),這是 Little Cyan Fish 聲稱從頂點 $i$ 開始搜尋所產生的 DFS 序。保證 $a_{i,1} = i$,且每一列 $a_i$ 都是 $1, 2, \dots, n$ 的一個排列。

保證所有測試資料的 $n^2$ 總和不超過 $4 \times 10^4$。

輸出格式

對於每筆測試資料,若不存在合適的圖,輸出單行 "No"。

否則,第一行輸出 "Yes"。下一行輸出一個整數 $m$ ($n - 1 \le m \le \frac{n(n-1)}{2}$),代表圖中的邊數。

接下來的 $m$ 行,每行包含兩個整數 $u$ 和 $v$ ($1 \le u, v \le n, u \neq v$),代表頂點 $u$ 與 $v$ 之間的一條無向邊。產生的圖必須是簡單且連通的,且從每個頂點 $i$ 開始的 DFS 序必須等於 $a_i$。

若有多個圖滿足要求,輸出其中任何一個即可。

範例

輸入 1

2
3
1 2 3
2 1 3
3 2 1
3
1 2 3
2 3 1
3 1 2

輸出 1

Yes
2
1 2
2 3
No

說明 1

在第一筆測試資料中,路徑 $1-2-3$ 是一個合法的圖:從頂點 1、2 和 3 開始的 DFS 序分別為 $[1, 2, 3]$、$[2, 1, 3]$ 和 $[3, 2, 1]$。在第二筆測試資料中,不存在合適的圖。

Discussions

About Discussions

The discussion section is only for posting: General Discussions (problem-solving strategies, alternative approaches), and Off-topic conversations.

This is NOT for reporting issues! If you want to report bugs or errors, please use the Issues section below.

Open Discussions 0
No discussions in this category.

Issues

About Issues

If you find any issues with the problem (statement, scoring, time/memory limits, test cases, etc.), you may submit an issue here. A problem moderator will review your issue.

Guidelines:

  1. This is not a place to publish discussions, editorials, or requests to debug your code. Issues are only visible to you and problem moderators.
  2. Do not submit duplicated issues.
  3. Issues must be filed in English or Chinese only.
Active Issues 0
No issues in this category.
Closed/Resolved Issues 0
No issues in this category.