算法提高 最小方差生成树
时间限制:1.0s 内存限制:256.0MB
问题描述
给定带权无向图,求出一颗方差最小的生成树。
输入格式
输入多组测试数据。第一行为N,M,依次是点数和边数。接下来M行,每行三个整数U,V,W,代表连接U,V的边,和权值W。保证图连通。n=m=0标志着测试文件的结束。
输出格式
对于每组数据,输出最小方差,四舍五入到0.01。输出格式按照样例。
样例输入
4 5
1 2 1
2 3 2
3 4 2
4 1 1
2 4 3
4 6
1 2 1
2 3 2
3 4 3
4 1 1
2 4 3
1 3 3
0 0
1 2 1
2 3 2
3 4 2
4 1 1
2 4 3
4 6
1 2 1
2 3 2
3 4 3
4 1 1
2 4 3
1 3 3
0 0
样例输出
Case 1: 0.22
Case 2: 0.00
Case 2: 0.00
数据规模与约定
1<=U,V<=N<=50,N-1<=M<=1000,0<=W<=50。数据不超过5组。
蓝桥杯的测试数据好像有问题。。。
#include <iostream>
#include <cstdio>
#include <vector>
#include <queue>
#include <map>
#include <cmath>
#include <stack>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#define FOR(i,x,n) for(long i=x;i<n;i++)
#define ll long long int
#define INF 0x3f3f3f3f
#define MOD 1000000007
#define MAX_N 60
#define MAX_M 1005 using namespace std; struct node{
int u,v;
double wPrior;
double wNow;
};
node graph[MAX_M];//储存边
int N,M;//点,边
int a[];//并查集数组 void init(){//并查集数组初始化
FOR(i,,){
a[i]=i;
}
} bool cmp(node a,node b){
return a.wNow<b.wNow;
} int findCaptain(int t){//寻找队长
if(a[t]==t){
return t;
}else{
return a[t]=findCaptain(a[t]);//路径压缩
}
} bool judge(int t1,int t2){//判断是否在一组内
return findCaptain(t1)==findCaptain(t2);
} void unionPoint(int t1,int t2){//合并两点
int tt=findCaptain(t1);
int ttt=findCaptain(t2);
a[tt]=ttt;
} double kruskal(int sum){//kruskal最小生成树
int edgeCount=;
double sum2=;
double sum3=;
double ave=sum*1.0/(N-);
FOR(i,,M){
graph[i].wNow=(graph[i].wPrior-ave)*(graph[i].wPrior-ave);
}
sort(graph,graph+M,cmp);//按边权从小到大排序
FOR(i,,M){
int t1=graph[i].u;
int t2=graph[i].v;
if(!judge(t1,t2)){
unionPoint(t1,t2);
edgeCount++;
sum2+=graph[i].wPrior;
sum3+=graph[i].wNow;
if(edgeCount==N-){
break;
}
}
}
if(sum==(int)sum2){
return sum3;
}else{
return INF*1.0;
}
} int main()
{
//freopen("input1.txt", "r", stdin);
//freopen("data.out", "w", stdout);
double t[];
int caseCount=;
double minVariance=INF*1.0;
while(~scanf("%d %d",&N,&M)&&(N+M)){
FOR(i,,M){
scanf("%d %d %lf",&graph[i].u,&graph[i].v,&graph[i].wPrior);
t[i]=graph[i].wPrior;
}
sort(t,t+M);
double minn=,maxx=;
FOR(i,,N-){//找出可能的最小的average*(n-1)
minn+=t[i];
}
FOR(i,M-N+,M){//找出最大的average*(n-1)
maxx+=t[i];
}
minVariance=INF*1.0;
FOR(i,minn,maxx+){
init();
double ans=kruskal(i);
minVariance=min(minVariance,ans);
}
printf("Case %d: %.2f\n",++caseCount,minVariance/(N-)); } //fclose(stdin);
//fclose(stdout);
return ;
}