analysis
很容易想到n方来暴力找一个连接方案,然后在连接后的图中跑Floyd,时间复杂度…
于是考虑如何优化n方暴力枚举后找新图直径的过程:
连接一条边后,新图直径可能是原来两个块中的直径中较大的那个或者新连接的这条边两端点在他们各自的块中的最远点距离之和和这条边的权值的和
于是我们可以预处理出两个直径和每个点的最远点,然后就可以用一个 O ( n ) O(n) O(n)的扫描得到答案了
估算一下,预处理的时间复杂度 O ( n 3 ) O(n^3) O(n3),于是整个程序的复杂度也就是 O ( n 3 ) O(n^3) O(n3)左右
(预处理定理:预处理可以降低时间复杂度,但是相应的代价是空间复杂度)
(预处理定理的本质:时间复杂度和空间复杂度总和相对守恒)
code
#include<bits/stdc++.h>
using namespace std;
#define loop(i,start,end) for(int i=start;i<=end;++i)
#define clean(arry,num) memset(arry,num,sizeof(arry))
#define copy(arry1,arry2) memcpy(arry1,arry2,sizeof(arry1))
#define lb(z) ((z)*(z))
const int maxn=200;
double inf;
int n;
struct pos{
double xi;
double yi;
pos():xi(0),yi(0){}
pos(double xi,double yi):xi(xi),yi(yi){}
};
inline double dis(pos a,pos b){
return sqrt(lb(a.xi-b.xi)+lb(a.yi-b.yi));
}
int bel[maxn];
double G[maxn][maxn];
pos zb[maxn];
char con[maxn];
int zyd[maxn];
double zj1=0,zj2=0;
void dfs(int u){
loop(v,1,n){
if(G[v][u]<1e9&&!bel[v]){
bel[v]=bel[u];
dfs(v);
}
}
}
void debug(){
loop(i,1,n){
loop(j,1,n){
printf("%.2lf ",G[i][j]);
}
printf("\n");
}exit(0);
}
int main(){
#ifndef ONLINE_JUDGE
freopen("datain.txt","r",stdin);
#endif
clean(bel,0);
clean(zyd,0);
scanf("%d",&n);
loop(i,1,n)
loop(j,1,n)
G[i][j]=1e9;
inf=G[1][1];
loop(i,1,n)
G[i][i]=0;
loop(i,1,n)
scanf("%lf%lf",&zb[i].xi,&zb[i].yi);
loop(i,1,n){
scanf("%s",con);
loop(j,0,n-1){
if(con[j]=='1')
G[i][j+1]=dis(zb[i],zb[j+1]);
}
}
int col=0;
loop(i,1,n){
if(!bel[i]){
bel[i]=++col;
dfs(i);
}
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>input & work out the belongings of the farm
loop(k,1,n){
loop(i,1,n){
loop(j,1,n){
G[i][j]=min(G[i][j],G[i][k]+G[k][j]);
}
}
}
loop(i,1,n){
double ld=0;
loop(j,1,n){
if(G[i][j]>ld&&G[i][j]<inf){
ld=G[i][j];
zyd[i]=j;
}
}
}
loop(i,1,n){
if(G[zyd[i]][i]>((bel[i]==1)?zj1:zj2))
((bel[i]==1)?zj1:zj2)=G[zyd[i]][i];
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>floyd & the longest distance & radium
double res=1e9,res2;
loop(i,1,n){
loop(j,1,n){
if(i==j||G[i][j]<inf)
continue;
res2=max(max(zj1,zj2),dis(zb[i],zb[j])+(G[i][zyd[i]]<inf?G[i][zyd[i]]:0)+(G[j][zyd[j]]<inf?G[j][zyd[j]]:0));
res=min(res,res2);
}
}
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>enumeration for i and j
printf("%.6lf",res);
return 0;
}