Codevs2038香甜的黄油题解

  • 题目就不粘了吧,大路边上就有。

  • 题解
    很直观的做法是枚举各个牧场跑最短路,把有奶牛的牧场的距离和加起来,求最小值。然后dijkstra堆优化时间复杂度 O(V2log2V+VE) 迅速通过。

  • Code

#include 
#include 
#include 
#include 
#include 
using namespace std;
const int maxn = 805, oo = 1000000000;
vector <int> g[maxn], w[maxn];
int N, P, C, ans, cow[maxn];
bool vis[maxn];
struct node
{
    int n, d;
    node(int n = 0, int d = oo) :n(n), d(d) {}
    bool operator < (const node& b) const
    {
        return d > b.d;
    }
};
node pnt[maxn];
void init()
{
    int x, y, z;
    scanf("%d%d%d", &N, &P, &C);
    for(int i = 1; i <= N; ++i)
    {
        scanf("%d", &cow[i]);
    }
    for(int i = 1; i <= C; ++i)
    {
        scanf("%d%d%d", &x, &y, &z);
        g[x].push_back(y);
        g[y].push_back(x);
        w[x].push_back(z);
        w[y].push_back(z);
    }
    ans = oo;
}
void work(int s)
{
    priority_queue  Q;
    memset(vis, 0, sizeof(vis));
    for(int i = 1; i <= P; ++i)
    {
        pnt[i] = node(i, oo);
    }
    pnt[s].d = 0;
    Q.push(pnt[s]);
    while(!Q.empty())
    {
        node t = Q.top();
        Q.pop();
        vis[t.n] = true;
        for(int i = 0; i < g[t.n].size(); ++i)
        {
            if((!vis[g[t.n][i]]) && (pnt[g[t.n][i]].d > t.d + w[t.n][i] || pnt[g[t.n][i]].d == oo))
            {
                pnt[g[t.n][i]].d = t.d + w[t.n][i];
                Q.push(pnt[g[t.n][i]]);
            }
        }
    }
    int sum = 0;
    for(int i = 1; i <= N; ++i)
    {
        sum += pnt[cow[i]].d;
    }
    ans = min(ans, sum);
}
int main()
{
    init();
    for(int i = 1; i <= P; ++i)
    {
        work(i);
    }
    printf("%d\n", ans);
    return 0;
}

你可能感兴趣的:(图结构,OI党坚毅的步伐)