Command Network 【POJ - 3164】【最小树形图】

题目链接


    一开始不知道有向图的最小生成树是怎样的,然后,用加上优先队列的Prime去跑了一遍,然后WA了两个小时,发现了似乎哪里有点不对啊,然后,我去博客上看了,哦!还有最小树形图这样的算法!然后,我先拿它去套了个模板过了HDU的2121之后,就开始敲这道题了,第一发WA了个"%.2lf"的故事,然后就过了。


#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN = 105;
const double INF = 1e9 + 7.;
int N, M;
struct node
{
    double x, y;
    node(double a=0, double b=0):x(a), y(b) {}
}a[maxN];
struct Eddge
{
    int u, v;
    double val;
    Eddge(int a=0, int b=0, double c=0):u(a), v(b), val(c) {}
}edge[maxN*maxN];
double Dis(int i, int j) { return sqrt( (a[i].x - a[j].x)*(a[i].x - a[j].x) + (a[i].y - a[j].y)*(a[i].y - a[j].y) ); }
double in[maxN];
int vis[maxN], pre[maxN], id[maxN];
double Dir_MST(int root, int V, int E)
{
    double ans = 0.;
    while(true)
    {
        for(int i=1; i<=V; i++) in[i] = INF;
        for(int i=1; i<=E; i++)
        {
            int u = edge[i].u, v = edge[i].v;
            if(in[v] > edge[i].val && v!=u)
            {
                in[v] = edge[i].val;
                pre[v] = u;
            }
        }
        for(int i=1; i<=V; i++)
        {
            if(i == root) continue;
            if(in[i] == INF) return -1;
        }
        int cnt = 0;    //环数
        memset(vis, -1, sizeof(vis));   memset(id, -1, sizeof(id));
        in[root] = 0;
        for(int i=1; i<=V; i++)
        {
            ans += in[i];
            int v = i;
            while(vis[v] != i && id[v] == -1 && v != root)
            {
                vis[v] = i;
                v = pre[v];
            }
            if(v != root && id[v] == -1)
            {
                cnt++;
                for(int u=pre[v]; u!=v; u=pre[u]) id[u] = cnt;
                id[v] = cnt;
            }
        }
        if(cnt == 0) return ans;
        for(int i=1; i<=V; i++) if(id[i] == -1) id[i] = ++cnt;
        for(int i=1; i<=E; i++)
        {
            int u = edge[i].u, v = edge[i].v;
            edge[i].u = id[u];  edge[i].v = id[v];
            if(id[u] != id[v]) edge[i].val -= in[v];
        }
        V = cnt;
        root = id[root];
    }
    return ans;
}
int main()
{
    while(scanf("%d%d", &N, &M)!=EOF)
    {
        for(int i=1; i<=N; i++) scanf("%lf%lf", &a[i].x, &a[i].y);
        for(int i=1; i<=M; i++)
        {
            int e1, e2;
            scanf("%d%d", &e1, &e2);
            edge[i] = Eddge(e1, e2, Dis(e1, e2));
        }
        double ans = Dir_MST(1, N, M);
        if(ans<0) printf("poor snoopy\n");
        else printf("%.2f\n", ans);
    }
    return 0;
}

 

你可能感兴趣的:(图论)