D. Fox And Jumping

纯粹的發表於2024-07-17

原題連結

題意簡述

在序列中選擇若干個數,使得其 \(gcd=1\) 且對應代價最小

實施

假設答案裡,\(a_i\) 是最後一個選的,代表 \(i\) 前面存在某些數的組合的 \(gcd\)\(a_i\) 互質

揹包+狀壓

再遍歷前面的數 \(j\) 和狀態,代表選 \(j\) 時,數 \(i\) 的質因子集合的狀態

code

#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll N=114514;

ll dp[1024];
ll yz[305][14];
ll cnt[306]={0};

void solve()
{
    int n;
    cin>>n;

    vector<int> c(n+5);

    for(ll i=1;i<=n;i++)
    {
        ll x;
        cin>>x;

        for(ll j=2;j*j<=x;j++)
        {
            if(x%j==0)
            {
                yz[i][++cnt[i]]=j;
                while(x%j==0) x/=j;
            }
        }
        if(x>1) yz[i][++cnt[i]]=x;

    }

    for(int i=1;i<=n;i++) cin>>c[i];


    ll ans=2e9;
    for(int i=1;i<=n;i++)
    {
        memset(dp,0x3f,sizeof dp);
        int bit=(1<<cnt[i])-1;
        dp[bit]=c[i];


        for(int j=1;j<i;j++)
        {
            ll tem=0;
            for(int x=1;x<=cnt[i];x++)
            {
                bool flag=0;
                for(int y=1;y<=cnt[j];y++)
                {
                    if(yz[i][x]==yz[j][y])
                    {
                        flag=1;
                        break;
                    }
                }
                if(flag) tem|=(1<<(x-1));
            }
            for(int k=0;k<=bit;k++) dp[k&tem]=min(dp[k&tem],dp[k]+c[j]);
        }

        ans=min(ans,dp[0]);
    }

    if(ans==2e9) cout<<"-1\n";
    else cout<<ans<<'\n';

}
int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int t=1;
    //cin>>t;
    while(t--) solve();
    return 0;
}


相關文章