题目链接:
http://acm.hdu.edu.cn/showproblem.php?pid=5211
题解:
1、筛法:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std; const int maxn=+;
const int INF=0x3f3f3f3f; int n;
int a[maxn],mmp[maxn];
vector<int> mat[maxn]; void init(){
for(int i=;i<maxn;i++) mat[i].clear();
memset(mmp,-,sizeof(mmp));
} int main(){
while(scanf("%d",&n)==&&n){
init();
int maxa=-;
for(int i=;i<=n;i++){
scanf("%d",a+i);
maxa=max(maxa,a[i]);
mmp[a[i]]=i;
}
int ans=;
for(int i=;i<=n;i++){
int minm=INF;
for(int j=;j*a[i]<=maxa;j++){
if(mmp[j*a[i]]!=-&&mmp[j*a[i]]>i){
minm=min(minm,mmp[j*a[i]]);
}
}
if(minm==INF) minm=;
ans+=minm;
}
printf("%d\n",ans);
}
return ;
}
2、倒着扫回来,不断刷新约数的值
#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std; const int maxn=+;
const int INF=0x3f3f3f3f; int n;
int a[maxn],mmp[maxn]; void init(){
memset(mmp,,sizeof(mmp));
} int main(){
while(scanf("%d",&n)==&&n){
init();
for(int i=;i<=n;i++) scanf("%d",a+i);
int ans=;
for(int i=n;i>=;i--){
ans+=mmp[a[i]];
for(int j=;j*j<=a[i];j++){
if(a[i]%j==){
mmp[j]=i;
mmp[a[i]/j]=i;
}
}
}
printf("%d\n",ans);
}
return ;
}