POJ 1456 Supermarket

本文介绍了一种结合贪心算法与并查集数据结构优化的解题策略,通过具体代码实现展示了如何高效解决特定问题。该方法首先使用贪心策略选择最优解,再利用并查集进行路径压缩及元素合并,从而达到优化效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解题思路:贪心+并查集优化

欢迎review
1 #include <iostream>
2  using namespace std;
3
4 int root[10001], pro[10001];
5 struct Prod{
6 int p, d;
7 }node[10000];
8 int cmp(const void *a, const void *b)
9 {
10 return (*(Prod*)a).p < (*(Prod*)b).p ? 1 : -1;
11 }
12 int findroot(int x)
13 {
14 if(root[x] != x)
15 root[x] = findroot(root[x]);
16 return root[x];
17 }
18 inline void Insert(Prod& cur)
19 {
20 int t, x = cur.d;
21 if(t = findroot(x))pro[t]=cur.p, root[t] = t - 1;
22 }
23 int main()
24 {
25 int n, i, ans;
26 while (scanf("%d", &n)==1)
27 {
28 for(i = 0; i < n; i++)
29 scanf("%d %d", &node[i].p, &node[i].d);
30 qsort(node, n, sizeof(Prod), cmp);
31 for(i=0; i < 10001; i++)root[i]=i, pro[i]=0;
32 for(i=0; i < n; i++) Insert(node[i]);
33 for(i=ans=0;i<10001; i++)ans+=pro[i];
34 printf("%d\n", ans);
35 }
36 return 0;
37 }

 

转载于:https://www.cnblogs.com/ltang/archive/2010/12/06/1898328.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值