P1194 买礼物

买礼物

问题分析
  • 都要买,问题在需要确定一个购买顺序
  • 用了某个优惠关系就在两点间连一条边,最后出来是一棵树
  • 那么用所有优惠关系建图,最后求最小生成树即可

  • 裸最小生成树
  • dist 初始化为 A
  • 如果边权大于A则边权赋值为A(坑点)
  • 建议用prim,因为是针对点的,每个点都要买
  • n = B, m = B * B;
  • 总结:B个点B^2条边的最小生成树,记得针对点

代码
#include 

#define pr pair
#define mk make_pair

using namespace std;

const int N = 1e5 + 1;

struct Node{
    int v,w,nxt;
    Node(){}
    Node(int _v, int _w, int _nxt) : v(_v), w(_w), nxt(_nxt){}
}edge[N << 2]; 

int n,m,top,cnt,cost;
int vis[N],head[N],dist[N];
int A,B;

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

priority_queue, greater > q;
void prim(){
    for(int i = 1; i <= n; ++i) dist[i] = A;
    dist[1] = A;
    q.push(mk(dist[1], 1));
    while(!q.empty()){
        int u = q.top().second;
        int d = q.top().first; q.pop();
        if(vis[u]) continue;
        vis[u] = 1;
        cnt += 1;
        cost += d;
        for(int i = head[u]; i; i = edge[i].nxt){
            int v = edge[i].v;
            int w = edge[i].w;
            if(w <= dist[v] && !vis[v])
                dist[v] = w,
                    q.push(mk(dist[v], v));
        }
        
    }
}

int main(){
    cin >> A >> B;
    n = B;
    m = B * B;
    for(int u = 1; u <= B; ++u){
        for(int v = 1; v <= B; ++v){
            int w;
                cin >> w;
                    if(w == 0 && u != v || w > A) w = A;
                        addedge(u, v, w);
        }
    }
    prim();
    printf("%d", cost);
    return 0;
}

转载于:https://www.cnblogs.com/Adventurer-H/p/11275108.html

你可能感兴趣的:(P1194 买礼物)