前言:一开始看到数据量这么大,我怎么拆分出因子,看了题解才发现要大减枝,但是如何拆分因数我还是要好好学一下
1 0 18 10^{18} 1018 的拆分因子有 1 0 5 10^5 105 的复杂度,再乘以 1 0 3 10^3 103 的数量,加上我们的大减枝刚刚好过关
题目地址
#include<bits/stdc++.h>
using namespace std;
#define int long long
int t;
int n;
const int N = (int)1e3+5;
int a[N];
int dis[N];
vector<int> fun(int x){
vector<int> e;
int i = 1;
while(i*i<=x&&i<=n){
if(x%i==0){
e.push_back(i);
if(i!=x/i){
if(x/i<=n) e.push_back(x/i);
}
}
i++;
}
return e;
}
signed main(){
cin >> n;
for(int i=1;i<=n;i++){
cin >> a[i];
dis[i] = INT_MAX;
}
dis[1] = 0;
queue<int> q;
q.push(1);
while(q.size()){
int u = q.front(); q.pop();
vector<int> e = fun(a[u]);
//cout << " u " << u << endl;
for(auto v:e){
//cout << " 因子有 " << v << endl;
if(u+v<=n&&dis[u]+1<dis[u+v]){
dis[u+v] = dis[u] + 1; q.push(u+v);
}
if(u-v>0&&dis[u]+1<dis[u-v]){
dis[u+v] = dis[u] + 1; q.push(u-v);
}
}
}
cout << dis[n];
return 0;
}