codeforces 643 C - Count Triangles
程序员文章站
2022-07-15 16:09:25
...
codeforces 643 C - Count Triangles
题面
大意
就是找三角形的个数,三角形三边满足 A <= x <= B <= y <= C <= z <= D 数量级是5e5
思路
我的思路比较数学一点吧。在[A,B]遍历最小边x,然后在O(1)的时间内算出当前这个值对应的个数。对于x而言,只要有x + y > z这个不等式成立即可满足三角形成立,因为暗含(x <= y <= z),考虑y两个极端的情况,y = B时,只要z满足 z <= x + B - 1即可,所以z的取值是[C, x + B - 1],不过这里需要讨论:
- x + B - 1 < c 此时取不到数
- c <= x + B - 1 <= d 此时个数为[C, x + B - 1]
- x + B - 1 > d 此时个数为[C, D]
同理对于y = C可以这样讨论,这样讨论之后还是不能直接求解,还需要一个累加的过程,这里先埋个坑… 等之后有空补上QaQ
总体上时间复杂度O(n) 空间复杂度O(1)
AC代码
int main() {
std::ios::sync_with_stdio(false);
cin.tie(0);
#ifdef MOON97
freopen("in.txt", "r", stdin);
#endif
ll a,b,c,d;
cin >>a>>b>>c>>d;
ll res = 0;
for (ll x = a; x <= b; x++) {
ll a1 = 0;
ll an = 0;
int pos2 = x + c - 1;
int pos1 = x + b - 1;
if (d >= pos2) {
if (c > pos1) {
a1 = 1;
an = pos2 - c + 1;
}
else {
a1 = pos1 - c + 1;
an = pos2 - c + 1;
}
res += (a1 + an) * (an - a1 + 1) / 2;
}
else if (d <= pos1){
res += (d - c + 1) * (c - b + 1);
}
else {
if (c > pos1) {
a1 = 1;
an = pos2 - c + 1;
res += (a1 + an) * (an - a1 + 1) / 2;
an = pos2 - d;
res -= (a1 + an) * (an - a1 + 1) / 2;
}
else {
a1 = pos1 - c + 1;
an = pos2 - c + 1;
res += (a1 + an) * (an - a1 + 1) / 2;
a1 = 1;
an = pos2 - d;
res -= (a1 + an) * (an - a1 + 1) / 2;
}
}
//if (x == 1) cout << a1 << " " << an <<endl;
}
cout << res << endl;
return 0;
}