题目名称:OO’s Sequence
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5288
Problem Description
OO has got a array A of size n ,defined a function f(l,r) represent the number of i (l<=i<=r) , that there's no j(l<=j<=r,j<>i) satisfy ai mod aj=0,now OO want to know
∑i=1n∑j=inf(i,j) mod (109+7).
Input
There are multiple test cases. Please process till EOF.
In each test case:
First line: an integer n(n<=10^5) indicating the size of array
Second line:contain n numbers ai(0<ai<=10000)
In each test case:
First line: an integer n(n<=10^5) indicating the size of array
Second line:contain n numbers ai(0<ai<=10000)
Output
For each tests: ouput a line contain a number ans.
Sample Input
5 1 2 3 4 5
Sample Output
23
题意:对每个区间f ( i , j ) 的个数求和,f ( i , j ) 满足在这个区间 [ i , j ] 内一个数(不包括它本身),没有数能被它整除。
思路(杭电的题解):定义两个数组L[ i ],R[ i ],表示第 i 个数左侧和右侧最接近它且值是a[ i ]因子的数字的位置,
那么第 i 个数能贡献的答案就是 (R[ i ] - i) * (i - L[ i ]),因此每个数字x都去枚举它的因子y,然后左右找一个
值是y且最接近x的数,然后用它的位置更新一下 L, R数组。时间复杂度O( nsqrt(a))。。
我看了题解,然后按它思路来,敲了一发,红果果的 t 了,,不知是不是我姿势不对
tle代码:
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<set>
#include<vector>
using namespace std;
typedef long long ll;
const int mod=1000000007;
set<ll> f[10005];
ll L[100005],R[100005],a[100005];
bool primer[10005];
int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int main()
{
int n;
for(ll i=1;i<=10000;i++)
for(ll j=1;j*i<=10000;j++)
f[i*j].insert(i);
while(scanf("%d",&n)!=EOF)
{
for(ll i=1;i<=n;i++)
{
a[i]=read();
L[i]=1;
R[i]=n;
}
for(ll i=1;i<=n;i++)
{
for(ll j=i-1;j>=1;j--)
{
if(f[a[i]].count(a[j]))
{
L[i]=j+1;
break;
}
}
for(ll j=i+1;j<=n;j++)
{
if(f[a[i]].count(a[j]))
{
R[i]=j-1;
break;
}
}
}
ll ans=0;
for(ll i=1;i<=n;i++)
{
ans=(ans%mod+(i-L[i]+1)*(R[i]-i+1)%mod)%mod;
}
printf("%lld\n",ans);
}
return 0;
}
于是我想正着来,从数字判断因子,那反着从因子判断是哪个的倍数
AC代码如下:
#include<cstdio>
#include<cstring>
#include<string>
#include<iostream>
#include<set>
#include<vector>
using namespace std;
typedef long long ll;
const int mod=1000000007;
set<ll> f[10005];
ll L[100005],R[100005],a[100005],vis[100005];
bool primer[10005];
ll read()
{
ll x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(ll i=1;i<=n;i++)
{
a[i]=read();
L[i]=1;
R[i]=n;
}
memset(vis,0,sizeof(vis)); //vis记录该数的倍数之前是否已经算过了,顺便记录位置
for(ll i=1;i<=n;i++)
{
for(ll j=a[i];j<=10000;j+=a[i])
{
if(vis[j]&&R[vis[j]]==n) //如果vis>0,说明a[i]的倍数j在之前出现过,说明a[i]是vis那位置的因子
R[vis[j]]=i-1;
}
vis[a[i]]=i;
}
memset(vis,0,sizeof(vis));
for(int i=n;i>0;i--)
{
for(ll j=a[i];j<=10000;j+=a[i])
{
if(vis[j]&&L[vis[j]]==1)
L[vis[j]]=i+1;
}
vis[a[i]]=i;
}
ll ans=0;
for(ll i=1;i<=n;i++)
{
ans=(ans%mod+(i-L[i]+1)*(R[i]-i+1)%mod)%mod;
}
printf("%lld\n",ans);
}
return 0;
}