B - No-Divisible Range 解説 by en_translator
Given an integer pair \((l,r)\) \((1\leq l\leq r\leq N)\), consider how we can determine if the condition is held.
For positive integers \(X\) and \(Y\), the conditions “\(X\) is a divisor of \(Y\)” and “the remainder when dividing \(Y\) by \(X\) is \(0\)” are equivalent. Therefore, the steps required are:
- find \(S=A_l+A_{l+1}+\cdots+A_r\), and
- for each \(l\leq i\leq r\), find the remainder when dividing \(S\) by \(A_i\). If any \(i\) yields a remainder \(0\), then \((l,r)\) does not satisfy the condition; otherwise, it does.
The two steps can be performed with for statements and basic operations. The computational complexity is \(O(N)\).
The number of candidate pairs \((l,r)\) is \(\frac{N(N+1)}{2}\), and they can be enumerated with for statements. For each of them we check the condition above, and count the number of applicable pairs. The time complexity is \(O(N^3)\), which is fast enough under the constraints of the problem.
Sample code in C++:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n;
int a[50]={};
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
int ans=0;
for(int i=0;i<n;i++){
for(int j=0;j<=i;j++){
int s=0;
for(int k=j;k<=i;k++)s+=a[k];
bool ok=true;
for(int k=j;k<=i;k++)if(s%a[k]==0)ok=false;
if(ok)ans++;
}
}
cout<<ans<<endl;
return 0;
}
Sample code in Python:
n=int(input())
a=list(map(int, input().split()))
ans=0
for i in range(n):
for j in range(i+1):
s=0
for k in range(j,i+1):
s+=a[k]
flag=True
for k in range(j,i+1):
if s%a[k]==0:
flag=False
if flag:
ans+=1
print(ans)
投稿日時:
最終更新: