题目相关
题目链接
AtCoder Beginner Contest 179 C 题,https://atcoder.jp/contests/abc179/tasks/abc179_c。
Problem Statement
Given is a positive integer N. How many tuples (A,B,C) of positive integers satisfy A×B+C=N.
Input
Input is given from Standard Input in the following format:
N
Output
Print the answer.
Samples1
Sample Input 1
3
Sample Output 1
3
Explaination
There are 3 tuples of integers that satisfy A×B+C=3: (A,B,C)=(1,1,2),(1,2,1),(2,1,1).
Samples2
Sample Input 2
100
Sample Output 2
473
Samples3
Sample Input 3
1000000
Sample Output 3
13969985
Constraints
- 2 ≤ N ≤ 10^6
- All values in input are integers.
题解报告
题目翻译
给出一个整数 N,问满足 A×B+C=N 的由正整数构成三元组有几个。
题目分析
看到题目后,尤其看了一下数据范围 N 的最大值是 1e6,第一反应又是一个 DFS 题目。但是使用递归实现的 DFS 必然是 TLE,因为数据大,递归将导致压栈太深。
再想了一下,可以用暴力枚举,如果直接枚举 A、B 和 C,这样就是 O(N^3) 的时间复杂度,肯定也是 TLE。其实只要优化一下枚举的次数,本题就可以通过。也就是让时间复杂度降低到 O(N^2) 级别或者更低。
根据题目描述我们可以知道 A×B+C=N,可以推倒出 ,这样我们可以只要枚举两个变量,计算出 C,然后再验证计算出的数据是否满足 A×B+C=N 即可。
也就是说,第一重循环从 1 到 N 来枚举 A,第二重循环从 1 到 来枚举 B,这样我们可以计算出 C,然后验证 A×B+C=N。这样设计的算法时间复杂度为调和级数。
样例数据分析
样例 1
根据输入,N=3。第一重循环从 1 到 3 枚举 A,第二重循环从 1 到 来枚举 B,这样我们可以写出以下的表格。
A | B | C | 是否满足 | ans |
1 | 1 | 2 | 满足 | 1 |
1 | 2 | 1 | 满足 | 2 |
1 | 3 | 0 | 不满足 | 2 |
2 | 1 | 1 | 满足 | 3 |
3 | 1 | 0 | 不满足 | 3 |
AC 参考代码
//https://atcoder.jp/contests/abc179/tasks/abc179_
#include <iostream>
using namespace std;
int main() {
int n;
cin>>n;
unsigned long long ans=0;
for (int a=1; a<n; a++) {
for (int b=1; b<=n/a; b++) {
int c=n-a*b;
if (c>0 && n==a*b+c) {
ans++;
}
}
}
cout<<ans<<"\n";
return 0;
}
时间复杂度
调和级数,也就是 O(nlogn)。