要求字典序最小所以要排两次序
#include <iostream>
#include <stdlib.h>#include <string.h>
#include <stdio.h>
#include <algorithm>
using namespace std;
#define maxn 110
#define INF 0x1f1f1f1f
struct node
{
int cost;
int u, v;
} Edge[maxn << 2];
node ans[maxn];
int tote,cnt;
int f[maxn];
void AddEdge( int u, int v, int cost)
{
Edge[tote].u = u;
Edge[tote].v = v;
Edge[tote++].cost = cost;
}
int cmp1( node a, node b)
{
if(a.cost != b.cost)
return a.cost < b.cost;
if(a.u != b.u)
return a.u < b.u;
else
return a.v < b.v;
}
int cmp2(node a, node b)
{
if(a.u != b.u)
return a.u<b.u;
else
return a.v < b.v;
}
int init( int n)
{
memset(f,-1,sizeof(f));
int val;
for( int i = 0; i < n; i++)
{
for( int j = 0; j < n; j++)
{
scanf("%d",&val);
if(val != 0 && j > i)
AddEdge(i,j,val);
}
}
}
int find( int x)
{
if(f[x] == -1) return x;
return f[x]=find(f[x]);
}
void slove()
{
int res = 0;
sort(Edge, Edge + tote, cmp1);
for( int i = 0; i < tote; i++)
{
int f1 = Edge[i].u;
int f2 = Edge[i].v;
int fa1 = find(f1);
int fa2 = find(f2);
if(fa1 != fa2)
{
ans[cnt++] = Edge[i];
f[fa1] = fa2;
}
}
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n;
scanf("%d",&n);
tote = cnt = 0;
init(n);
slove();
if(cnt != n-1)
printf("-1\n");
else
{
sort(ans, ans + cnt, cmp2);
for( int i = 0; i < cnt; i++)
printf("%d %d%c",ans[i].u+1, ans[i].v+1, i == cnt - 1 ?'\n' : ' ');
}
}
}