Vladislav invented a new algorithm of the distributed key construction.
The distributed key consists of 2n numerical sequences of length n. To construct the key Vladislav gets some permutation p of length n2. Next step is to put the elements of p into a square matrix a. The first n elements of p form the first row of a, next n elements form the second row, etc. Finally, 2n numerical sequences of the distributed key are rows and columns of the matrix a.
These 2n sequences were given to Vladislav in some arbitrary order. He spent a while trying to come up with an algorithm for recovering the permutation. Try to restore the permutation before the end of the round!
Input
The first input line contains one integer n (1 ≤ n ≤ 100).
Each of the next 2n lines contains n integers from 1 to n2, rows and columns of the matrix a in some order.
It is guaranteed that the input is correct, there is at least one suitable permutation p.
Output
Print a permutation p of integers from 1 to n2.
Example
Input
2
1 2
1 3
2 4
3 4
Output
1 2 3 4
很暴力的一题…..其实这一题只看每行的第一个数就好了,其他的都可以无视。
思维点在于,先找到第一位出现两次的那个数,然后把这两条数据随便拿一个放在开头,另一个竖着挂。再把剩下的数据一个个贴上去,如果出现贴不上上去的情况,就换一下,把竖着的那个贴到开头。直接输出!
public class Main {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = reader.nextInt();
int len = 2 * n;
int[][] input = new int[len][n];
for (int i = 0; i < len; i++) {
for (int j = 0; j < n; j++) {
input[i][j] = reader.nextInt();
}
}
int row = 0;
int col = 0;
for (int i = 0; i < len; i++) {
for (int j = i + 1; j < len; j++) {
if (input[i][0] == input[j][0]) {
row = i;
col = j;
break;
}
}
}
Set<Integer> visited = new HashSet<>();
visited.add(row);
visited.add(col);
for (int i = 1; i < n; i++) {
boolean canFill = false;
for (int j = 0; j < len; j++) {
if (!visited.add(j)) {
continue;
}
canFill = input[j][0] == input[col][i];
if (canFill) {
break;
}
}
if (!canFill) {
int temp = row;
row = col;
col = temp;
break;
}
}
for (int i = 0; i < n; i++) {
out.print(input[row][i]);
if (i < n - 1) {
out.print(" ");
}
}
for (int i = 1; i < n; i++) {
for (int j = 0; j < len; j++) {
if (j == row || j == col) {
continue;
}
if (input[j][0] == input[col][i]) {
for (int k = 0; k < n; k++) {
out.print(" " + input[j][k]);
}
break;
}
}
}
out.close();
}
}