hdu 5288 (小技巧)

OO’s Sequence


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=1nj=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)
 

Output
For each tests: ouput a line contain a number ans.
 

Sample Input
5 1 2 3 4 5
 

Sample Output
23
 

題目大意: 給出n個數,求在任意區間內,i<>j 並且i%j!=0 的i的個數 

思        路: 利用pre數組存儲每個數出現的序號
                    借用此從左到右,便利出每個數據的因子,找到在數據範圍最右面的那個因子所在的序號
                   同理可知道左面的。
                  
 具體看代碼:
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;
const int mod = 1e9+7;
#define ll long long
#define N 100005
ll left[N],right[N];
int n,num[N],pre[N];

int main()
{
    while(scanf("%d",&n)!=EOF){
        for(int i=1;i<=n;i++){
            scanf("%d",&num[i]);
            left[i]=1;
            right[i]=n;
        }
          
        memset(pre,0,sizeof(pre));
        for(int i=1;i<=n;i++){
            for(int j=num[i];j<=10000;j+=num[i]){
                if(pre[j]&&right[pre[j]]==n)
                    right[pre[j]]=i-1;
            }
            pre[num[i]]=i;
        }
        memset(pre,0,sizeof(pre));
        for(int i=n;i>=1;i--){
            for(int j=num[i];j<=10000;j+=num[i]){
                if(pre[j]&&left[pre[j]]==1)
                    left[pre[j]]=i+1;
            }
            pre[num[i]]=i;
        }

        long long ans=0;
        for(int i=1;i<=n;i++)
            ans = (ans%mod+(long long)(i-left[i]+1)*(right[i]-i+1)%mod)%mod;
        printf("%lld\n",ans);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章