CF1996D题解
D.Fun
题目描述
Given two integers n
and x, find the number of triplets (a,b,c) of positive integers such that ab+ac+bc≤nand a+b+c≤x.
Note that order matters (e.g. (1,1,2) and (1,2,1) are treated as different) and a, b, c must be strictly greater than 0.
Input:
The first line contains a single integer t(1≤t≤1e4) — the number of test cases.Each test case contains two integers n and x(1≤n,x≤1e6).It is guaranteed that the sum of n over all test cases does not exceed 106 and that the sum of x over all test cases does not exceed 1e6.
Output:
Output a single integer — the number of triplets (a,b,c) of positive integers such that ab+ac+bc≤n and a+b+c≤x.
题目概述
给定两个整数n和x,求满足以下要求的三元组(a,b,c)的个数:
- ab+ac+bc<=n
- a+b+c<=x
- a,b,c都为正整数
- 三元组是有序的
解题思路
首先先看数据的范围过大,三重循环查找会超时,我们看看是否有什么方法可以优化一下。尝试将三重循环转为二重循环,三个未知数的话可以尝试变为两个未知数枚举,将第三个数利用关系用其他两个数来表示。
尝试用a,b计算c的可行范围:
因为
ab+ac+bc<=n
所以
ab+c(a+b)<=n
(a+b)c<=n-ab
c<=(n-ab)/(a+b)
又因为
a+b+c<=x
所以c的又一个范围为
c<=x-a-b
综上,c的范围为:
c的最大值=min((n-ab)/(a+b),x-a-b),并且c>=1
故,只要c的最大值大于1,那么c=1到c=c_max都是合法的解,一共有c_max个满足条件的三元组(对于某一对a,b),将c_max计数到ans中。当枚举完所有的a,b时,得到的ans即是结果
AC Code
#include <bits/stdc++.h>
#define endl '\n'
#define int long long
void solve(){
int n, x;
std::cin >> n >> x;
int ans = 0;
for (int i = 1; i <= std::min(n, x);++i){
for (int j = 1; i * j <= n && i + j <= x;++j){
int num = std::min((n - i * j) / (i + j), x - (i + j));
ans += num;
}
}
std::cout << ans << endl;
}
signed main()
{
std::ios_base::sync_with_stdio(0);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
int _;
//_=1;
std::cin>>_;
while(_--){
solve();
}
return 0;
}

浙公网安备 33010602011771号