POJ 1715(超时)

#include <stdio.h>
#include <math.h>
#include <algorithm>
using namespace std;
#define arraysize 751
#define array 1001  //已修建的路
int xi[arraysize];
int yi[arraysize];
int final[arraysize];
int nodenum[arraysize];
typedef struct node
{
 int v;
 int u;
 double w;
}node;
node edges[arraysize*arraysize];
node record[arraysize];
double distance(int x1,int y1,int x2,int y2)
{
 return sqrt(double((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)));
}
bool cmp(node a,node b)
{
 return a.w<b.w;
}
int findroot(int n)
{
 if(final[n]==n)
  return n;
 else
 {
  final[n] = findroot(final[n]);
 }
 return final[n];
}
int main()
{
 //freopen("1.txt","r",stdin);
 int N,M;
 int edgesnum = 0;
 while(scanf("%d",&N)!=EOF)
 {
  int i,j;
  for(i=1;i<N+1;++i)
  {
   scanf("%d%d",&xi[i],&yi[i]);
  }  
  for(i=1;i<N+1;++i)
  {
   for(j=i+1;j<N+1;++j)
   {
    edgesnum++;
    edges[edgesnum].v = i;
    edges[edgesnum].u = j;
    edges[edgesnum].w = distance(xi[i],yi[i],xi[j],yi[j]);
   }
  }
  scanf("%d",&M); 
  for(i=1;i<M+1;++i)
  {
   int a,b,tempt;
   scanf("%d%d",&a,&b);
   if(a>b)
   {
    tempt = a;
    a = b;
    b = tempt;
   }
   tempt = (a-1)*N-(a-1)*a/2+(b-a); //此处不要将(a-1)提取出来
   edges[tempt].w = 0;
   /*for(int j=1;j<edgesnum+1;++j)
   {
    if((edges[j].v == a && edges[j].u == b)|| (edges[j].u==a && edges[j].v ==b))
    {
     edges[j].w = 0;
     break;
    }
   }*/
  }
  sort(edges+1,edges+edgesnum+1,cmp);
  for(i=1;i<N+1;++i)
  {
   final[i] = i;
   nodenum[i] = 1;
  }
  int num = 0;
  for(i=1;i<edgesnum+1;++i)
  {
   int start = edges[i].v;
   int end = edges[i].u;
   double w = edges[i].w;
   int rootstart = findroot(start);
   int rootend = findroot(end);
   if(rootstart!=rootend)
   {
    num++;
    record[num].v = start;
    record[num].u = end;
    record[num].w = w;
    if(final[rootstart]>=final[rootend])
    {
     final[rootend] = rootstart;
     nodenum[rootstart] += nodenum[rootend];
    }
    else
    {
     final[rootstart] = rootend;
     nodenum[rootend] += nodenum[rootstart];
    }
   }
   if(num == N-1)
    break;
  }
  if(num == N-1)
  {
   for(i=1;i<num+1;++i)
   {
    if(record[i].w == 0)
     continue;
    printf("%d %d\n",record[i].v,record[i].u);
   }
  }
 }
 return 0;
}

posted @ 2010-04-30 22:30  北海小龙  阅读(206)  评论(0编辑  收藏  举报