http://acm.split.hdu.edu.cn/showproblem.php?pid=5726
数字越多GCD后的值越小,而且只能继续变小,利用这一原则可以用map储存数值一旦数值变换就更改段的起点。再储存下每个值的个数。
#include<iostream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <map>
using namespace std;
int n,num[100005];
vector<pair<int,int> >gcd[100005];
map<int,long long>Ans;
int GCD(int x, int y)
{
return y ? GCD(y, x % y) : x;
}
int main()
{
int T,Test=0;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&num[i]);
}
int last;
Ans.clear();
for(int k=1;k<=n;k++){
last=0;
for(int j=0;j<gcd[k-1].size();j++){
int u=gcd[k-1][j].first,v=gcd[k-1][j].second;
u=GCD(u,num[k]);
if(u==last){
continue;
}
last=u;
gcd[k].push_back(make_pair(u,v));
}
if(num[k]!=last){
gcd[k].push_back(make_pair(num[k],k));
}
for(int i=0;i<gcd[k].size();i++){
Ans[gcd[k][i].first]+=(i!=gcd[k].size()-1?gcd[k][i+1].second:k+1)-gcd[k][i].second;
}
}
int m;
scanf("%d",&m);
printf("Case #%d:\n", ++Test);
for(int i=0,u,v,k;i<m;i++){
scanf("%d%d",&u,&v);
for(k=0;k<gcd[v].size();k++){
if(u<gcd[v][k].second){
break;
}
}
printf("%d %I64d\n",gcd[v][k-1].first,Ans[gcd[v][k-1].first]);
}
for (int i = 0; i <= n; ++i)
{
gcd[i].clear();
}
}
return 0;
}