[詳解]圖論模型轉化的思惟題:AGC017E - Jigsaw

Problem Statement

We have \(N\) irregular jigsaw pieces. Each piece is composed of three rectangular parts of width \(1\) and various heights joined together. More specifically:ide

  • The \(i\)-th piece is a part of height \(H\), with another part of height \(A_i\) joined to the left, and yet another part of height \(B_i\) joined to the right, as shown below. Here, the bottom sides of the left and right parts are respectively at \(C_i\) and \(D_i\) units length above the bottom side of the center part.

img

Snuke is arranging these pieces on a square table of side \(10^{100}\). Here, the following conditions must be held:spa

  • All pieces must be put on the table.
  • The entire bottom side of the center part of each piece must touch the front side of the table.
  • The entire bottom side of the non-center parts of each piece must either touch the front side of the table, or touch the top side of a part of some other piece.
  • The pieces must not be rotated or flipped.

Determine whether such an arrangement is possible.code

Constraints

  • \(1 \leq N \leq 100000\)
  • \(1 \leq H \leq 200\)
  • \(1 \leq A_i \leq H\)
  • \(1 \leq B_i \leq H\)
  • \(0 \leq C_i \leq H - A_i\)
  • \(0 \leq D_i \leq H - B_i\)
  • All input values are integers.

Solution

首先,該模型的可行性沒法快速檢驗,咱們必須將它轉換爲咱們能處理的模型。blog

考慮用圖論模型刻畫可行性:用一條有向邊\((l,r)\)刻畫一個拼圖,須要知足:積木\((l,r)\)右邊可以有拼圖\((l',r')\)等價於\(r=l'\)three

原題的限制

咱們發現:積木的邊界有兩種狀況:直接着地或不直接着地,分別對應\(C\)\(D\)是否等於\(0\)。須要分狀況討論。ip

積木\((A,B,C,D)\)右邊可以有拼圖\((A',B',C',D')\)當且僅當:ci

  • \(D = 0\)\(B = C'\),或
  • \(C' = 0\)\(D = A'\),或
  • \(D = 0\)\(C' = 0\)

最後一種很難刻畫成邊的連通的形態,因此咱們暫時捨棄這一條。get

一條路徑的合法當且僅當:input

  • 最左邊的拼圖的\(C=0\),且
  • 最右邊的拼圖的\(D=0\)

圖論模型的構造與探索

通過試驗,發現能夠這麼定義:(點的編號爲\(-H,\dots,-1\)\(1,\dots,H\)it

  • \(l=\)
    • \(A_i\),當\(C_i = 0\)時。
    • \(-C_i\),當\(C_i\ne 0\)時。
  • \(r=\)
    • \(-B_i\),當\(D_i = 0\)時。(注意負號在這裏)
    • \(D_i\),當\(D_i\ne 0\)時。

這樣,一條知足題目要求的路徑就是一條從正數通向負數的路徑了。

問題轉化爲:一張圖是否能夠被拆成若干條這樣的路徑?

先考慮最明顯的入度與出度的限制:

  • 編號爲正的頂點知足:出度>=入度
  • 編號爲負的頂點知足:出度<=入度

考慮一些極端狀況:(對圖來講:圖中有若干連通份量;存在環、樹等特殊圖論模型)當圖爲環時,顯然不存在這樣的路徑拆分。推而廣之,咱們發現只要圖存在一切歐拉回路,都不存在這樣的路徑拆分。換句話說,對任何一個弱連通份量,都存在頂點使得出度!=入度

再手玩了幾個例子,發現這些應該是刻畫可行性所需的全部必要條件了,咱們經過構造一個可行解來證實它是充分的:

對每個弱連通份量,找到第一個出度>入度的正數點(一定存在——爲何?)。一直向下走直到不可以走爲止。此時一定停留在一個負數點(爲何?)。咱們將這個路徑抽出來,圖的剩下部分依然知足咱們以前所說的性質嗎?假若不知足,則此時整個圖中一定有一個或多個歐拉回路(由於此時度數的限制依然知足)。因爲圖原本是弱連通的,則途中一定通過一個與某個歐拉回路相鏈接的點,咱們將這個迴路包括進咱們的路徑就好了。對全部的迴路都執行這個操做以後,剩下的圖(若是有的話)將依然知足這些性質。重複此操做便可構造出一個可行解。

至此,咱們只須要對每一個弱連通份量中的全部點檢查一遍是否知足以上條件就好了。用並查集/DFS均可以。

https://atcoder.jp/contests/agc017/submissions/21464597

相關文章
相關標籤/搜索