10.15 区间贪心

· · 个人记录

P8787 [蓝桥杯 2022 省 B] 砍竹子

如果用题中给的公式,用 6 次就可以将 LONG_LONG_MAX 变为 1 所以,直接暴力枚举变化次数,就可以过了 若与右边相等,就说明这俩可以一起砍,于是直接不计算 若不相等,就说明得单独计算,于是答案增加

Code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,ans;
ll a[200005],cnt[200005];

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    for(int i = 1;i <= n;i++){
        cin >> a[i]; 
        ll y = 0,x = a[i];
        while(x != 1){
            y++;
            x = sqrt(x / 2 + 1);
        }
        cnt[i] = y;
    }
    for(int i = 6;i >= 1;i--){
        for(int j = 1;j <= n;j++){
            if(cnt[j] == i){
                if(a[j] != a[j + 1]){
                    ans++;
                }
                a[j] = sqrt(a[j] / 2 + 1);
                cnt[j]--;
            } 
        }
    }
    cout << ans;
    return 0;
}

B3833 [NICA #2] 爱与不爱

经过一番 简单的 艰难的思考,可以发现,所有的都可以变为 1 1 1 1 1 1 1 1 ... 2^sum

上面的结论是这么来的: 首先将一个数一直除二,直到变为 1 ,然后再将其他所有数一直除二,这个数一直乘二 最后就得到了 1 1 1 1 1 1 1 1 ... 2^sum

此时在均分一下即可

Code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,ans,sum;

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    for(int i = 1;i <= n;i++){
        ll x;
        cin >> x;
        ll cnt = 0;
        while(x > 1){
            cnt++;
            x /= 2;
        }
        sum += cnt;
    }
    for(int i = 1;i <= n;i++){
        ans += (1 << (sum / n + (sum % n >= i)));
    }
    cout << ans;
    return 0;
}

P11124 [ROIR 2024 Day 2] 数组划分

既然要求不能相隔一个质数,那我们就直接从根源上解决问题——在同一组的两个数质因子个数同奇偶,这样在同一组的就不可能乘上一个质数到达别的数。

Code

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,ans,sum;

bool work(ll x){
    ll cnt = 0;
    for(int i = 2;i * i <= x;i++){
        while(x % i == 0){
            cnt++;
            x /= i;
        }
    }
    if(x > 1){
        cnt++;
        x = 1;
    }
    return (cnt & 1);
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin >> n;
    while(n--){
        ll x;
        cin >> x;
        if(work(x)){
            cout << "1 ";
        }else{
            cout << "2 ";
        }
    }
    return 0;
}