zoukankan      html  css  js  c++  java
  • poj2377

    最大生成树,注意边数组开二倍大小。注意不连通输出-1;

    View Code
    #include <iostream>
    #include
    <cstdio>
    #include
    <cstdlib>
    #include
    <cstring>
    #include
    <queue>
    using namespace std;

    #define maxn 1005
    #define maxm 20005

    struct Edge
    {
    int v, next, w;
    Edge(
    int vv, int nn, int ww) :
    v(vv), next(nn), w(ww)
    {
    }
    Edge()
    {
    }
    } edge[maxm
    * 2];

    int head[maxn], count;
    bool vis[maxn];
    int ans = 0;
    int m, n;

    bool operator< (const Edge &a, const Edge &b)
    {
    return a.w < b.w;
    }

    void addedge(int u, int v, int w)
    {
    edge[count].next
    = head[u];
    edge[count].v
    = v;
    edge[count].w
    = w;
    head[u]
    = count;
    count
    ++;
    }

    void input()
    {
    scanf(
    "%d%d", &n, &m);
    for (int i = 0; i < m; i++)
    {
    int a, b, c;
    scanf(
    "%d%d%d", &a, &b, &c);
    a
    --, b--;
    addedge(a, b, c);
    addedge(b, a, c);
    }
    }

    void prim(int src)
    {
    priority_queue
    <Edge> pq;
    int pre = 0;
    Edge temp;
    pq.push(Edge(src,
    0, 0));
    while (!pq.empty())
    {
    do
    {
    temp
    = pq.top();
    pq.pop();
    }
    while (!pq.empty() && vis[temp.v]);
    if (vis[temp.v])
    return;
    vis[temp.v]
    = true;
    pre
    = temp.v;
    ans
    += temp.w;
    for (int i = head[pre]; i != -1; i = edge[i].next)
    if (!vis[edge[i].v])
    pq.push(edge[i]);
    }
    }

    int main()
    {
    //freopen("t.txt", "r", stdin);
    memset(head, -1, sizeof(head));
    memset(vis,
    0, sizeof(vis));
    count
    = 0;
    input();
    prim(
    0);
    bool ok = true;
    for (int i = 0; i < n; i++)
    if (!vis[i])
    {
    ok
    = false;
    break;
    }
    if (ok)
    printf(
    "%d\n", ans);
    else
    printf(
    "%d\n", -1);
    return 0;
    }

  • 相关阅读:
    Oracle:ORA-12154: TNS:could not resolve the connect identifier specified
    asp.net mvc4 controller
    asp.net MVC4 学习(一)
    Nuget用法
    asp.net mvc4 新特性
    arcgis for silverlight 相关学习资料整理
    (转)ASP.NET 4.0 尚未在 Web 服务器上注册
    EasyUI TreeGrid
    CollabNetSubversionEdge 4.0.4教程
    C# 混淆 反编译
  • 原文地址:https://www.cnblogs.com/rainydays/p/2056252.html
Copyright © 2011-2022 走看看