- #include <stdio.h>
- #define INF 200000000
- #define MAX 751
- int path[MAX];
- int matrix[MAX][MAX];
- int main()
- {
- int x[MAX],y[MAX];
- int N,M;
- int p1,p2;
- int temp1,temp2;
- int i,j;
- int cost[MAX];
- int min;
- int u;
- scanf("%d",&N);
- for(i=1;i<=N;i++)
- scanf("%d%d",&x[i],&y[i]);
- for(i=1;i<=N;i++)
- for(j=i;j<=N;j++)
- if(i==j)
- matrix[i][i]=INF;
- else
- {
- temp1=x[i]-x[j];
- temp2=y[i]-y[j];
- matrix[j][i]=matrix[i][j]=temp1*temp1+temp2*temp2;
- }
- scanf("%d",&M);
- for(i=1;i<=M;i++)
- {
- scanf("%d%d",&p1,&p2);
- matrix[p1][p2]=matrix[p2][p1]=0;
- }
- for(i=1;i<=N;i++)
- {
- cost[i]=matrix[1][i];
- path[i]=1;
- }
- cost[1]=-1;
- for(i=1;i<=N-1;i++)
- {
- min=INF;
- for(j=1;j<=N;j++)
- if(cost[j]!=-1 && cost[j]<min)
- {
- u=j;
- min=cost[j];
- }
- if(min>0)
- printf("%d %d/n",path[u],u);
- cost[u]=-1;
- for(j=1;j<=N;j++)
- if(cost[j]!=-1 && cost[j]>matrix[u][j])
- {
- path[j]=u;
- cost[j]=matrix[u][j];
- }
- }
- return 0;
- }
- /*18 4543344(5) xiaofengsheng 2404K 79MS C++ 1028B 2009-01-09 15:38:56
- 当边稠密时最好用prim,而不宜用Kruskal
- (这里是已有添加好边的minimum spanning tree problem)
- 经过几次提交发现:
- 1.typedef struct point
- {
- int x;
- int y;
- }point;
- 用结构体稍微比数组 int x[MAX],y[MAX]; 慢,不过结构体结构清晰;
- 2.if(i==j)
- matrix[i][i]=INF;
- 开始时处理的不好,
- for(i=1;i<=N;i++)
- for(j=1;j<=N;j++)
- matrix[i][j]=INF;
- 另外,多亏suikay代码的有益启发!thanks...
- */
- #include <stdio.h>
- #define INF 200000000
- #define MAX 751
- typedef struct point
- {
- int x;
- int y;
- }point;
- point p[MAX];
- int path[MAX];
- int matrix[MAX][MAX];
- void main()
- {
- int N,M;
- int p1,p2;
- int temp1,temp2;
- int i,j;
- int cost[MAX];
- int min;
- int u;
- scanf("%d",&N);
- for(i=1;i<=MAX;i++)
- for(j=1;j<=MAX;j++)
- matrix[i][j]=INF;
- for(i=1;i<=N;i++)
- scanf("%d%d",&p[i].x,&p[i].y);
- for(i=1;i<=N;i++)
- for(j=i+1;j<=N;j++)
- {
- temp1=p[i].x-p[j].x;
- temp2=p[i].y-p[j].y;
- matrix[j][i]=matrix[i][j]=temp1*temp1+temp2*temp2;
- }
- scanf("%d",&M);
- for(i=1;i<=M;i++)
- {
- scanf("%d%d",&p1,&p2);
- matrix[p1][p2]=matrix[p2][p1]=0;
- }
- //prim
- for(i=1;i<=N;i++)
- {
- cost[i]=matrix[1][i];
- path[i]=1;
- }
- cost[1]=-1;
- for(i=1;i<=N-1;i++)
- {
- min=INF;
- for(j=1;j<=N;j++)
- if(cost[j]!=-1 && cost[j]<min)
- {
- u=j;
- min=cost[j];
- }
- if(min>0)
- printf("%d %d/n",path[u],u);
- cost[u]=-1;
- for(j=1;j<=N;j++)
- if(cost[j]!=-1 && cost[j]>matrix[u][j])
- {
- path[j]=u;
- cost[j]=matrix[u][j];
- }
- }
- }
- //最开始的code
pku 1751
最新推荐文章于 2019-01-08 01:48:28 发布