[Luogu P1265] road construction

Luogu P1265
had a beginning Kruskal I used ...... but due to a double 8 bytes, so the MLE.
It is very easy to find a minimum spanning tree problem.
It is noted that in the subject to a second limitation, i.e., the case where there is only a unique ring is an equilateral polygon.
But if it is equilateral polygons then this restriction did not give and give absolutely no difference ......
so that's a bare minimum spanning tree problem.
Since the Kruskal need to record the right side of statistics, but the problem is given a complete graph, a lot of space overhead.
Prim can be calculated when needed, no early records, general overhead space.
In fact this is the Prim algorithm and Kruskal's algorithm on the principle of different.
Prim's algorithm is the center point of the algorithm, Kruskal's algorithm is based on the center side.
In the sparse graph Kruskal outperformed Prim, but it would be more appropriate in view of dense and full figure Prim.

#include<cstdio>
#include<cmath>
#define inf 0x3f3f3f3f3f3f3f3f
using namespace std;
long long n,cost[5005],x[5005],y[5005];
bool vis[5005];
double ans;
void First()
{
    for (int i=0;i<=n;i++) cost[i]=inf;
    cost[1]=0;
}
void Prim()
{
    for (int i=1;i<=n;i++)
    {
        long long mincost=inf,m=0;
        for (int j=1;j<=n;j++)
            if (mincost>cost[j]&&!vis[j]) 
            {
                mincost=cost[j];
                m=j;
            }
        vis[m]=true;
        ans+=sqrt(cost[m]);
        for (int j=1;j<=n;j++)
            if ((x[m]-x[j])*(x[m]-x[j])+(y[m]-y[j])*(y[m]-y[j])<cost[j]&&!vis[j]) 
                cost[j]=(x[m]-x[j])*(x[m]-x[j])+(y[m]-y[j])*(y[m]-y[j]);
    }
}
int main()
{
    scanf("%lld",&n);
    for (int i=1;i<=n;i++)
        scanf("%lld%lld",&x[i],&y[i]);
    First();
    Prim();
    printf("%.2f",ans);
    return 0;
}

Guess you like

Origin www.cnblogs.com/notscience/p/11957415.html