最新文章
这里会显示最新的几篇文章摘要。
记录生活,分享知识,与你一起成长。
这里会显示最新的几篇文章摘要。
You are given integers N and K. Find the number of triples (a,b,c) of positive integers not greater than N such that a+b,b+c and c+a are all multiples of K. The order of a,b,c does matter, and some of them can be the same.
Constraints
1≤N,K≤2×105
N and K are integer
这个题目要求找出满足条件的三元组 ((a, b, c)),使得:
我们可以通过「数论+分类讨论」的方式求解这个问题。
如果 ( x+y ) 是 ( K ) 的倍数,我们可以用「同余类」来分析:
设 ( x \equiv r_x \pmod{K} ),即 ( x ) 对 ( K ) 取模的余数是 ( r_x )。
那么 ( a+b, b+c, c+a ) 都是 ( K ) 的倍数,可以得到:
[
(a + b) \equiv 0 \pmod{K}
]
[
(b + c) \equiv 0 \pmod{K}
]
[
(c + a) \equiv 0 \pmod{K}
]
这意味着:
[
2a \equiv 2b \equiv 2c \equiv 0 \pmod{K}
]
所以 ( a, b, c ) 的取模值必须相同,并且等于 ( 0 ) 或 ( K/2 )(如果 ( K ) 是偶数)。
然后,满足条件的三元组数目:
#include <iostream>
using namespace std;
typedef long long ll;
int main() {
ll N, K;
cin >> N >> K;
ll C0 = N / K; // 统计余数为 0 的个数
ll Ck2 = (K % 2 == 0) ? (N / K + (N % K >= K / 2)) : 0; // 统计余数为 K/2 的个数
ll result = C0 * C0 * C0;
if (K % 2 == 0) {
result += Ck2 * Ck2 * Ck2;
}
cout << result << endl;
return 0;
}
整个算法的时间复杂度为 ( O(1) ),因为只涉及简单的除法和乘法运算,适用于 ( N, K \leq 200000 ) 的约束。
这道题的核心在于通过取模分析数的分布,并利用数学公式快速计算符合条件的三元组个数。