您的位置:首页 > 其它

zoj3204 connect them 最小生成树 暴力

2017-08-09 14:12 337 查看
Connect themTime Limit:1 Second      Memory Limit:32768 KBYou have n computers numbered from 1 ton and you want to connectthem to make a small local area network (LAN). All connections are two-way (that is connecting computersi andjis the same as connecting computersj andi). The cost of connecting computeriand computerj iscij. You cannot connect some pairsof 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.InputThere 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-thinteger 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=cjib94c,cii= 0, 1 <=i,j <=n.OutputFor 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 thelexicographicallysmallest one (see hints for the definition of "lexicography small") If you cannot connect them, just output "-1" in the line.Sample Input
2
3
0 2 3
2 0 5
3 5 0
2
0 0
0 0
Sample Output1 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;}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: