• prim算法记录路径


    题目链接:https://vjudge.net/contest/66965#problem/H

    代码:

    #include<iostream>
    #include<string>
    #include<cstring>
    #include<iomanip>
    #include<cmath>
    #include<stack>
    #include<queue>
    #include<algorithm>
    #include<map>
    #include<stdio.h>
    #include<vector>
    using namespace std;
    # define inf 0x3f3f3f3f
    # define maxn 5000+10
    # define ll long long
    double dis[maxn][maxn];
    int vis[maxn];
    double te[maxn];
    int head[maxn];
    int n;
    struct node
    {
        double  x,y;
    } q[maxn];
    double cal(int t1,int t2)
    {
        return sqrt((q[t1].x-q[t2].x)*(q[t1].x-q[t2].x)*1.0+(q[t1].y-q[t2].y)*(q[t1].y-q[t2].y)*1.0);
    }
    void prim()
    {
        memset(vis,0,sizeof(vis));
        for(int i=1; i<=n; i++)
        {
            te[i]=dis[1][i];
            head[i]=1;
        }
        //head[1]=0;
        for(int j=1; j<=n; j++)
        {
            double minn=inf;
            int po=0;
            for(int i=1; i<=n; i++)
            {
                if(vis[i]==0&&te[i]<minn)
                {
                    minn=te[i];
                    po=i;
                }
            }
            if(minn!=0&&po!=0)//这个时候这个点的最短距离已经找到了,直接输出就行了。
            {
                printf("%d %d
    ",head[po],po);
            }
            vis[po]=1;
            for(int i=1; i<=n; i++)
            {
                if(vis[i]==0&&te[i]>dis[po][i])
                {
                    te[i]=dis[po][i];
                    head[i]=po;
                }
            }
        }
    }
    int main()
    {
        scanf("%d",&n);
        for(int i=1; i<=n; i++)
        {
            scanf("%lf%lf",&q[i].x,&q[i].y);
        }
        for(int i=1; i<=n; i++)
        {
            for(int j=1; j<=n; j++)
            {
                if(i==j)
                {
                    dis[i][j]=0.0;
                    continue;
                }
                dis[i][j]=cal(i,j);
            }
        }
        int m;
        scanf("%d",&m);
        for(int i=1; i<=m; i++)
        {
            int t1,t2;
            scanf("%d%d",&t1,&t2);
            dis[t2][t1]=dis[t1][t2]=0.0;
        }
        prim();
        return 0;
    }
    
  • 相关阅读:
    Python核心编程——正则表达式
    Python 随笔之Redis
    我的第一个Python随笔
    python练习题-day20
    python练习题-day19
    python练习题-day18
    python练习题-day16
    python练习题-day15
    python练习题-day14
    python练习题-day13
  • 原文地址:https://www.cnblogs.com/letlifestop/p/10262870.html
Copyright © 2020-2023  润新知