Make It One CodeForces - 1043F (数论,最短路,好题)
大意: 给定序列$a$, 求最小子集, 使得gcd为1.
对于数$x$, 素因子多少次幂是无关紧要的, 这样就可以用一个二进制数来表示.
$x$取$gcd$后的二进制状态最多$2^7$, 可以暴力枚举后继$y$, 可以得到方案数为$sum=\sum\limits_{i=1}^n[gcd(a_i,x)=y]=\sum\limits_{d|\frac{x}{y}}\mu(d)cnt[yd]$.
($cnt[x]$为能被$x$整除的$a_i$个数).
若$sum>0$则可以达到这个后继. 这样跑一次$bfs$即可.
$bfs$的复杂度是A072047的三次幂求和, 打个表发现是N为3e5时只有5412256, 可以通过.
#include <iostream> #include <sstream> #include <algorithm> #include <cstdio> #include <math.h> #include <set> #include <map> #include <queue> #include <string> #include <string.h> #include <bitset> #define REP(i,a,n) for(int i=a;i<=n;++i) #define PER(i,a,n) for(int i=n;i>=a;--i) #define hr putchar(10) #define pb push_back #define lc (o<<1) #define rc (lc|1) #define mid ((l+r)>>1) #define ls lc,l,mid #define rs rc,mid+1,r #define x first #define y second #define io std::ios::sync_with_stdio(false) #define endl '\n' #define DB(a) ({REP(__i,1,n) cout<<a[__i]<<' ';hr;}) using namespace std; typedef long long ll; typedef pair<int,int> pii; const int P = 1e9+7, P2 = 998244353, INF = 0x3f3f3f3f; ll gcd(ll a,ll b) {return b?gcd(b,a%b):a;} ll qpow(ll a,ll n) {ll r=1%P;for (a%=P;n;a=a*a%P,n>>=1)if(n&1)r=r*a%P;return r;} ll inv(ll x){return x<=1?1:inv(P%x)*(P-P/x)%P;} inline int rd() {int x=0;char p=getchar();while(p<'0'||p>'9')p=getchar();while(p>='0'&&p<='9')x=x*10+p-'0',p=getchar();return x;} //head const int N = 3e5+10; int n, mu[N], gpf[N], d[N], cnt[N]; vector<int> fac[N], dv, val; queue<int> q; void dfs(int d, int s, int num) { val[s] = num; if (d!=dv.size()) dfs(d+1,s,num),dfs(d+1,s|1<<d,num*dv[d]); } void solve(int x) { dv.clear(); int t = x; while (t!=1) { int z = gpf[t]; while (t%z==0) t/=z; dv.pb(z); } int mx = 1<<dv.size(); val.resize(mx); dfs(0,0,1); REP(i,0,mx-1) { int y = val[i]; int sum = 0, r = ~i&(mx-1); for (int j=r; j; j=(j-1)&r) { sum += mu[val[j]]*cnt[val[j]*y]; } sum += mu[1]*cnt[y]; if (sum&&!d[y]) { q.push(y); d[y] = d[x]+1; } } } int main() { mu[1] = gpf[1] = 1; REP(i,1,N-1) { if (!gpf[i]) for (int j=i;j<N;j+=i) gpf[j]=i; for (int j=i;j<N;j+=i) fac[j].pb(i); for (int j=2*i;j<N;j+=i) mu[j]-=mu[i]; } scanf("%d", &n); REP(i,1,n) { int t; scanf("%d", &t); set<int> s; while (t!=1) s.insert(gpf[t]),t/=gpf[t]; for (int x:s) t*=x; if (d[t]) continue; d[t] = 1; for (int x:fac[t]) ++cnt[x]; q.push(t); } if (d[1]) return puts("1"),0; while (q.size()) { int x = q.front(); q.pop(); solve(x); } printf("%d\n", d[1]?d[1]:-1); }