Dr Who's Banquet
Time limit1sMemory limit256 MB
Build a chat graph whose vertex degrees equal the given wishes with the stated greedy construction, or print fail.
Problem
Dr Who is holding a banquet and invites several guests. Guest is happy when he chats with exactly of the other guests. A guest never chats with himself, and any two guests either chat with each other or they do not. Pair the guests so that every guest is happy, or report that no such arrangement exists.
Input
The input holds several data sets, one data set per line. A line holds the integers separated by single spaces, where is the number of chat partners guest wants. The guests on a line are numbered to in the order they appear. and . The input ends at the end of the file.
Output
Print one block for each data set. If every guest can be made happy, print the matrix , where when guests and chat and otherwise. Print each row on its own line and separate the values of a row by single spaces. If no arrangement makes every guest happy, print fail. Print one empty line after each block.
Several matrices can satisfy the same wish list, so only the matrix produced by the construction below counts as correct.
Give each guest a counter set to and put every guest in the pool. While some guest in the pool has , repeat this. Take the guest of the pool with the largest , and among ties the one with the smaller number. Order the remaining guests of the pool by from large to small, breaking ties by the smaller number, and pair with the first of them. Subtract from the counter of each new partner, set to , and remove from the pool. The matrix is complete once every guest left in the pool has . This construction pairs everybody whenever a valid arrangement exists.