P1194 买礼物

Portal.

最小生成树。

一个貌似比较常见的图论建模。对于每个物品可以抽象成一个点,建立超级源点。把每个物品与超级源点连一条边权为 A A A 的边表示直接购买这个物品,在把有优惠关系的一对物品连一条边权为优惠价格 K K K 的边。

这样转化之后,买到所有的物品就等价于使整张图连通。要求最小代价,求最小生成树即可。

注意区分 A A A 和 B B B。

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxn=3e5+5;
struct edge{int u,v,w;}e[maxn];
int fa[maxn];

bool cmp(edge a,edge b){return a.w<b.w;}

int find(int x){return x==fa[x]?x:fa[x]=find(fa[x]);}

int main()
{
	int A,B;cin>>A>>B;
	for(int i=1;i<=B;i++) e[i]=(edge){0,i,A},fa[i]=i;
	int cnt=B;
	for(int i=1;i<=B;i++)
		for(int j=1;j<=B;j++)
		{
			int K;cin>>K;
			if(K) e[++cnt]={i,j,K};
		}
	sort(e+1,e+cnt+1,cmp);
	int tot=0;
	ll ans=0;
	for(int i=1;i<=cnt;i++)
	{
		int fx=find(e[i].u),fy=find(e[i].v);
		if(fx==fy) continue;
		tot++,fa[fx]=fy,ans+=e[i].w;
		if(tot==B) break;
	}
	cout<<ans;
	return 0;
}
相关推荐
钮钴禄·爱因斯晨1 天前
数据结构|图论:从数据结构到工程实践的核心引擎
c语言·数据结构·图论
heeheeai2 天前
kotlin图算法
算法·kotlin·图论
杨小码不BUG4 天前
CSP-J/S初赛知识点精讲-图论
c++·算法·图论··编码·csp-j/s初赛
(❁´◡`❁)Jimmy(❁´◡`❁)5 天前
【Trie】 UVA1401 Remember the Word
算法·word·图论
qq_418247886 天前
论文阅读:TEMPORAL GRAPH NETWORKS FOR DEEP LEARNING ON DYNAMIC GRAPHS
论文阅读·人工智能·深度学习·图论
希望201715 天前
图论基础知识
算法·图论
行走的bug...16 天前
用图论来解决问题
算法·图论
Athenaand16 天前
代码随想录算法训练营第50天 | 图论理论基础、深搜理论基础、98. 所有可达路径、广搜理论基础
算法·图论
_Coin_-17 天前
算法训练营DAY60 第十一章:图论part11
算法·图论
Athenaand17 天前
代码随想录算法训练营第62天 | Floyd 算法精讲、A * 算法精讲 (A star算法)、最短路算法总结篇、图论总结
算法·图论