并查集 – D – Recommendations

就是有n组,每组的数量是num,只能增加数字,增加的代价为t,求能使所有组的数量都不同的最小代价。

#include<bits/stdc++.h> 
#define N 200005
#define endl '\n' 
#define _for(i,a,b) for(int i=a;i<b;i++)
using namespace std;
typedef long long ll;  
struct Node{
    int num; ll t;
    bool operator < (const Node &o){ 
        return t>o.t;
    }
}a[N];
map<int,int > F;
int find(int k){
    if(F[k]==0){
        return k;
    }
    else return F[k]=find(F[k]); 
}
void link(int a,int b){
    int fa=find(a),fb=find(b);
    if(fa!=fb) F[fa]=fb;
}
ll res;
int main(){    
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);     
    int n ; cin>>n;
    _for(i,1,n+1) cin>>a[i].num;
    _for(i,1,n+1) cin>>a[i].t;
    sort(a+1,a+n+1);
    _for(i,1,n+1){
        int tem=a[i].num;
        int to= find(tem);
        link(to,to+1);
        if( to == tem ) ;
        else { 
            res+= 1ll*(to-tem)*a[i].t;
        }
    }
    cout<<res<<endl;
    return 0;
} 

 

 

#include<bits/stdc++.h> #define N 200005#define endl '\n' #define _for(i,a,b) for(int i=a;i<b;i++)using namespace std;typedef long long ll;  struct Node{int num; ll t;bool operator < (const Node &o){ return t>o.t;}}a[N];map<int,int > F;int find(int k){if(F[k]==0){return k;}else return F[k]=find(F[k]); }void link(int a,int b){int fa=find(a),fb=find(b);if(fa!=fb) F[fa]=fb;}ll res;int main(){    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);     int n ; cin>>n;_for(i,1,n+1) cin>>a[i].num;_for(i,1,n+1) cin>>a[i].t;sort(a+1,a+n+1);_for(i,1,n+1){int tem=a[i].num;int to= find(tem);link(to,to+1);if( to == tem ) ;else { res+= 1ll*(to-tem)*a[i].t;}}cout<<res<<endl;return 0;} 

原文链接: https://www.cnblogs.com/SunChuangYu/p/12364501.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    并查集 - D - Recommendations

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/331849

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午6:14
下一篇 2023年3月1日 下午6:14

相关推荐