题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5288
解法:
定义两个数组L[i],R[i],表示第i数左侧和右侧最接近它且值是a[i]因子的数字的位置,那么第i个数能贡献的答案就是(R[i]-i)*(i-L[i]),因此每个数字x都去枚举它的因子y,然后左右找到一个值是y且最接近x的数,然后用他的位置更新一下L,R数组。时间复杂度O(nsqrt(a))。
代码:
#include <stdio.h>
#include <ctime>
#include <math.h>
#include <limits.h>
#include <complex>
#include <string>
#include <functional>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <list>
#include <bitset>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <ctime>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <time.h>
#include <ctype.h>
#include <string.h>
#include <string>
#include <assert.h>
#pragma comment(linker,"/STACK:1024000000,1024000000")
using namespace std;
const int MAXN = 100010;
const int MOD = 1e9 + 7;
int n;
int a[MAXN];
int L[MAXN], R[MAXN];
int pre[MAXN];
vector<int> g[MAXN];
void init()
{
for (int i = 1; i <= 10000; i++)
{
g[i].clear();
for (int j = 1; j*j <= i; j++)
{
if (i%j == 0)
{
g[i].push_back(j);
if (j*j != i)
g[i].push_back(i / j);
}
}
}
}
int main()
{
init();
while (~scanf("%d", &n))
{
for (int i = 1; i <= n; i++)
scanf("%d",&a[i]);
memset(L,0,sizeof(L));
memset(R,0,sizeof(R));
memset(pre,0,sizeof(pre));
for (int i = 1; i <= n; i++)
{
int tmp = a[i];
int pos = 0;
for (int j = 0; j < g[tmp].size(); j++)
{
int t2 = g[tmp][j];
pos = max(pre[t2],pos);
}
pre[tmp] = i;
L[i] = pos;
}
for (int i = 1; i <= 10000; i++) pre[i] = 100001;
for (int i = n; i >= 1;i--)
{
int tmp = a[i];
int pos = n + 1;
for (int j = 0; j < g[tmp].size(); j++)
{
int t2 = g[tmp][j];
pos = min(pre[t2], pos);
}
pre[tmp] = i;
R[i] = pos;
}
long long ans = 0;
for (int i = 1; i <= n; i++)
ans += (long long)(R[i] - i) * (i - L[i]) % MOD;
printf("%lld\n", ans%MOD);
}
return 0;
}