九度oj 题目1144:Freckles,不能通过,为什么超时间? 30C

#include
#include
#include
using namespace std;
const int maxn = 5000;
const double INF = 1000000000;
bool vis[maxn] = {false};
double x[maxn],y[maxn];
int n ;
int father[maxn];
struct Node{
double u,v;
double cost;
}edge[maxn];
int index;
bool cmp(Node a,Node b){
return a.cost<b.cost;
}
void init(){

for(int i = 0;i < n;i++){
for(int j = 0;j <= i;j++){
edge[index].u = i;
edge[index].v = j;
edge[index++].cost = sqrt((x[i]-x[j])*(x[i]-x[j])+(y[i]-y[j])*(y[i]-y[j]));
}
}
}

int findfather(int x){
while(x!=father[x]){
x = father[x];
}
return x;
}

double Krustral(){
double ans = 0,num = 0;
for(int i = 0; i< n;i++){
father[i] = i;
}
for(int i = 0; i < index;i++){
int faa = findfather(edge[i].u);
int fab = findfather(edge[i].v);
if(faa!=fab){
father[faa] = fab;
ans+=edge[i].cost;
num++;
if(index-1==num) break;
}
}
return ans;
}

int main(){
while(scanf("%d",&n)!=EOF&&n!=0){
index = 0;
fill(x,x+maxn,0);
fill(y,y+maxn,0);
for(int i = 0;i < n;i++){
scanf("%lf %lf",&x[i],&y[i]);
}
init();
sort(edge,edge+index,cmp);
double a = Krustral();
printf("%.2lf\n",a);
}
return 0;
}


九度OJ:http://ac.jobdu.com/problem.php?pid=1144

3个回答

可能是你算法不优化

参考:http://www.ithao123.cn/content-5538295.html

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问