zoj3204 connect them 最小生成树 暴力

来源:互联网 发布:北方工业大学知乎 编辑:程序博客网 时间:2024/05/20 08:42
Connect them

Time Limit: 1 Second      Memory Limit:32768 KB

You have n computers numbered from 1 ton and you want to connect them to make a small local area network (LAN). All connections are two-way (that is connecting computersi andj is the same as connecting computersj andi). The cost of connecting computeri and computerj iscij. You cannot connect some pairs of computers due to some particular reasons. You want to connect them so that every computer connects to any other one directly or indirectly and you also want to pay as little as possible.

Given n and eachcij , find the cheapest way to connect computers.

Input

There are multiple test cases. The first line of input contains an integerT (T <= 100), indicating the number of test cases. ThenT test cases follow.

The first line of each test case contains an integern (1 <n <= 100). Thenn lines follow, each of which containsn integers separated by a space. Thej-th integer of thei-th line in thesen lines iscij, indicating the cost of connecting computersi andj (cij = 0 means that you cannot connect them). 0 <= cij <= 60000,cij =cji,cii = 0, 1 <=i,j <=n.

Output

For each test case, if you can connect the computers together, output the method in in the following fomat:

i1j1i1j1 ......

where ik ik (k >= 1) are the identification numbers of the two computers to be connected. All the integers must be separated by a space and there must be no extra space at the end of the line. If there are multiple solutions, output thelexicographically smallest one (see hints for the definition of "lexicography small") If you cannot connect them, just output "-1" in the line.

Sample Input

230 2 32 0 53 5 020 00 0

Sample Output

1 2 1 3-1
 1:每个点都必须加入,而且不可能有环,所以生成一棵树。
 2:最小生成树。
 3:数据小,直接暴力。
 4:反正我暴力之后也想不明白O(n^4)居然只要60ms。600ms我比较好接受,难道暴力出奇迹?
#include<cstdio>#include<cstdlib>#include<iostream>#include<algorithm>#include<memory.h>using namespace std;const int inf=1e9;int map[101][101];int ans,n;int tnum,tfrom,tto;bool used[101];int _Sin(){char c=getchar();while(c<'0'||c>'9') c=getchar();int s=0;while(c>='0'&&c<='9'){s=s*10+c-'0';c=getchar();}return s;}struct in{int L,R;}a[101];bool cmp(in a,in b){if(a.L==b.L) return a.R<b.R;return a.L<b.L;}void _update(){memset(used,false,sizeof(used));return ;}void _in(){n=_Sin();for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) map[i][j]=_Sin();}bool _solve(){used[1]=true;for(int s=1;s<n;s++){  tnum=inf;  for(int i=1;i<=n;i++){if(used[i]){    for(int j=1;j<=n;j++){if(!used[j]&&map[i][j]!=0&&map[i][j]<tnum){tnum=map[i][j];tfrom=i;tto=j;}}}  }  if(tnum==inf) return false;  used[tto]=true;  if(tfrom>tto) swap(tfrom,tto);  a[s].L=tfrom;  a[s].R=tto;}sort(a+1,a+n,cmp);return true;}int main(){int T;T=_Sin();while(T--){_update();_in();if(!_solve()) printf("-1\n");else { printf("%d %d",a[1].L,a[1].R); for(int i=2;i<n;i++)  printf(" %d %d",a[i].L,a[i].R); printf("\n");}}return 0;}