(kruskal算法复习+模板)Eddy's picture
題目:
Eddy begins to like painting pictures recently ,he is sure of himself to become a painter.Every day Eddy draws pictures in his small room, and he usually puts out his newest pictures to let his friends appreciate. but the result it can be imagined, the friends are not interested in his picture.Eddy feels very puzzled,in order to change all friends ‘s view to his technical of painting pictures ,so Eddy creates a problem for the his friends of you.
Problem descriptions as follows: Given you some coordinates pionts on a drawing paper, every point links with the ink with the straight line, causes all points finally to link in the same place. How many distants does your duty discover the shortest length which the ink draws?
Input
The first line contains 0 < n <= 100, the number of point. For each point, a line follows; each following line contains two real numbers indicating the (x,y) coordinates of the point.
Input contains multiple test cases. Process to the end of file.
Output
Your program prints a single real number to two decimal places: the minimum total length of ink lines that can connect all the points.
Sample Input
3
1.0 1.0
2.0 2.0
2.0 4.0
Sample Output
3.41
分析與解答
題意:就是給你幾個點的坐標,讓你求一下每個點都經過的最短距離。我們知道點坐標,就可以把兩點之間的距離求出來,此時我們可以看作給了兩點和一個邊,求最短路,這就轉化成連通工程那一道題。我寫這個突然發現我把那個kruskal算法給忘了
先上一個kruskal模板
代碼參考:https://blog.csdn.net/qq_30591245/article/details/77094961
#include<cstdio> #include<cstring> #include<algorithm> #include<cmath> using namespace std; int pre[505]; struct data {int x,y;double len; } a[25005]; struct Point {double x,y; }b[25005]; void init() {for(int i=0; i<505; i++)pre[i]=i; } int Find(int x) {if(pre[x]!=x)return pre[x]=Find(pre[x]);return x; } //void Merge(int x,int y) //{ // int X=Find(x); // int Y=Find(y); // if(X!=Y) // pre[X]=Y; //} int cmp(data a,data b) {return a.len<b.len; } double Distance(Point a,Point b) {return sqrt(1.0*(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y)); } int main() {int n;while(~scanf("%d",&n)){init();for(int i=1;i<=n;i++){scanf("%lf%lf",&b[i].x,&b[i].y);}int cnt=0;for(int i=1;i<n;i++){for(int j=i+1;j<=n;j++){a[cnt].x=i;a[cnt].y=j;a[cnt].len=Distance(b[i],b[j]);//printf("%f\n",a[cnt].len);++cnt;}}//printf("%d\n",cnt);sort(a,a+cnt,cmp);double res=0;for(int i=0;i<cnt;i++){int X=Find(a[i].x);int Y=Find(a[i].y);if(X!=Y){pre[X]=Y;// printf("%f\n",a[i].len);res+=a[i].len;}}printf("%.2f\n",res);} }總結
以上是生活随笔為你收集整理的(kruskal算法复习+模板)Eddy's picture的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python julian date_P
- 下一篇: linux include 编译,lin