HDU 5288 OO’s Sequence (二分查找)

来源:互联网 发布:java商城项目 编辑:程序博客网 时间:2024/05/16 09:09

OO’s Sequence

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 569    Accepted Submission(s): 205


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
51 2 3 4 5
 

Sample Output
23题意:求对于所有i<=j,数列a[i],a[i+1]...a[j]中不能整除其他所有元素的元素数量的总和。思路:2015多校赛第一场,比赛中想不出,多校赛的简单题对我等渣渣实在不简单。过后看题解,定义两个数组l[i], r[i],表示第i个数左侧和右侧最接近它且值是a[i]因子的数字的位置。第i个数只能在l[i]+1到r[i]-1区间的包含a[i]的子区间有贡献,除了这些区间a[i]都因其因子的存在而没有贡献。贡献值为(i-l[i])*(r[i]-i)。因此问题转为求l[i],r[i]。具体如代码所示,过程中用到二分查找。
#include <stdio.h>#include <stdlib.h>#include <algorithm>#include <math.h>#include <string.h>#include <vector>#define MOD 1000000007using namespace std;int l[100009], r[100009], a[100009];vector<int> w[10009];int findr(int k, int n, int i){    int lb=0, ub=n-1;    while(ub-lb>1)    {        int mid=(ub+lb)/2;        if(w[i][mid] > k)        {            ub=mid;        }        else        {            lb=mid;        }    }    return w[i][ub];}int findl(int k, int n, int i){    int lb=0, ub=n+1;    while(ub-lb>1)    {        int mid=(ub+lb)/2;        if(w[i][mid] < k)        {            lb=mid;        }        else        {            ub=mid;        }    }    return w[i][lb];}int main(){    int n;    while(~scanf("%d", &n))    {        for(int i=0; i<10009; i++)        {            w[i].clear();            w[i].push_back(0);        }        for(int i=1; i<=n; i++)        {            scanf("%d", &a[i]);            l[i]=0, r[i]=n+1;            w[a[i]].push_back(i);        }        for(int i=0; i<10009; i++)        {            w[i].push_back(n+1);        }        long long ans=0;        for(int i=1; i<=n; i++)        {            for(int j=1; j<=sqrt(a[i]); j++)            {                if(a[i]%j != 0)                    continue;                else                {                    int c=a[i]/j;                    l[i]=max(l[i], findl(i, w[c].size(), c));                    r[i]=min(r[i], findr(i, w[c].size(), c));                    c=j;                    l[i]=max(l[i], findl(i, w[c].size(), c));                    r[i]=min(r[i], findr(i, w[c].size(), c));                }            }            ans+=(long long)(i-l[i])*(r[i]-i);        }        printf("%lld\n", ans%MOD);    }    return 0;}


0 0