Supermarket POJ - 1456【并查集】
作者:互联网
Supermarket POJ - 1456
思路:贪心 + 并查集优化,先把数对按照价值从大到小排序,然后依次枚举,枚举到不能用的就跳过,有点像kruskal?
具体代码如下
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdio>
using namespace std;
const int N = 10010;
int n;
int p[N];
struct Node{
int a, b;
}node[N];
bool cmp(Node x, Node y){
return x.a > y.a;
}
int find(int x)
{
if(p[x]==-1)return x;
return p[x]=find(p[x]);
}
int main(){
while(~scanf("%d", &n)){
memset(p, -1, sizeof p);
int x, y;
for(int i=0; i<n; ++i){
scanf("%d%d", &x, &y);
node[i] = {x, y};
}
sort(node, node + n, cmp);
long long res = 0;
for(int i=0;i<n;i++)
{
int t=find(node[i].b);
if(t>0)//t=0表示前node[i].b天已经全用了
{
res+=node[i].a;
p[t]=t-1;
}
}
printf("%lld\n", res);
}
return 0;
}
标签:node,Node,return,int,查集,1456,POJ,include,find 来源: https://blog.csdn.net/qq_50702668/article/details/113729529