Gym - 100513K Treeland

Treeland is an ancient country located on the territory of the modern Berland many many years ago. It is a well-known fact that Treeland consisted of n cities connected with n - 1 bidirectional roads. It was possible to travel from any city to any other one along the roads. The cities were numbered from 1 to n.

Nowadays we do not know what cities were connected by roads directly, but recently archaeologists have found new information that can help to reconstruct the road network of Treeland.

They found an ancient library with the diaries of a well-known traveler Biklouho-Baclay. The diaries contain interesting information: for each city i there is a list of all cities in the order of non-decreasing distance from i. The distances are calculated assuming that each road has length 1, so a distance between cities is the minimum number of roads to travel between them.

Formally, for each city i there is a list  containing a permutation of cities (numbers from 1 to n) in such order that d(i, ci, j) ≤ d(i, ci, j + 1) for every j = 1... n - 1, where d(x, y) is a distance between cities x and y. Obviously, ci, 1 = i for each i. The cities that are equidistant from i can be listed in any order.

Your task is to restore a possible road network consistent with the found lists.

Input

The input consists of several test cases. The first line contains integer number t(1 ≤ t ≤ 1000) — the number of test cases.

Then t blocks follow, each describing a single test case. The first line of a block contains integer number n (2 ≤ n ≤ 2000) — the number of cities. The following nlines contain lists Ci, one list per line.

It is guaranteed that the required road network exists for each test case. The sum of n over all test cases doesn't exceed 2000.

Output

For each test case print n - 1 lines describing roads. Each line should contain a pair of cities connected with a road. You may print the roads and cities in a pair in any order. Print a blank line after the output of a test case.

If there are many solutions, print any of them.

Examples

Input

3
2
1 2
2 1
5
1 4 5 3 2
2 3 4 1 5
3 4 2 5 1
4 3 1 5 2
5 4 3 1 2
3
1 3 2
2 1 3
3 1 2

Output

2 1 

2 3
3 4
5 4
4 1 

2 1
3 1

题意:一个顶点数为N的树,对于每个点i,我们按照与i的距离从小到大给出顺序,即dis i ,现在让你输出N-1条边,即还原这棵树。

题解:我们以某一点为根节点,从距离最远的点与其父代生成边,每操作完一个点标记一下,若在给u节点,找父节点的时候已经被标记了,说明该点是u的子代,继续找下一个就可以了

#include<bits/stdc++.h>
using namespace std;
const int N=2000+10;
int a[N][N],vis[N];
int n;
int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
    {
        memset(vis,0,sizeof(vis));
        scanf("%d",&n);
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++)
                scanf("%d",&a[i][j]);
        int k=n;
        while(k>1)
        {
            int u=a[1][k],id=2;
            vis[u]=1;
            k--;
            while(vis[a[u][id]]) id++;
            printf("%d %d\n",u,a[u][id]);
        }
    }
	return 0;
}

猜你喜欢

转载自blog.csdn.net/mmk27_word/article/details/84560566