C. Count Triangles

题目链接:https://codeforces.com/contest/1355/problem/C

 

 

 

 

第一种做法:

我们假设三角形的三条边 x,y,z   x + y > z 

我们考虑枚举 x + y 的和 【枚举的时候可以优化一下,枚举 [max(c+1,a+b) , b+c] 】,如果知道了 x 我们就可以知道 y

所以我们考虑 x ,单纯的考虑 x 的范围 [a,b] 或者针对 y 从而考虑 x 的范围 [i-c,i-b]

 

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>

#define ll long long
#define ull unsigned long long
#define ls nod<<1
#define rs (nod<<1)+1
#define pii pair<int,int>
#define mp make_pair
#define pb push_back
#define INF 0x3f3f3f3f
#define max(a, b) (a>b?a:b)
#define min(a, b) (a<b?a:b)


const double eps = 1e-8;
const int maxn = 2e5 + 10;
const ll MOD = 998244353;
const int mlog=20;

int sgn(double a) { return a < -eps ? -1 : a < eps ? 0 : 1; }

using namespace std;



int main() {
    ll a,b,c,d;
    ll ans = 0;
    cin >> a >> b >> c >> d;
    for (ll i = max(c+1,a+b);i <= b+c;i++) {
        ans += (min(d+1,i)-c) * (min(i-b,b)-max(a,i-c)+1);
    }
    cout << ans << endl;
    return 0;
}

 

第二种方法:

我们直接考虑差分 + 前缀和的方法,

针对 x 我们可以直接枚举出 x + y 的范围

然后再反过来前缀和可以得到 sum[i] 代表 >= i 的个数

 

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>

#define ll long long
#define ull unsigned long long
#define ls nod<<1
#define rs (nod<<1)+1
#define pii pair<int,int>
#define mp make_pair
#define pb push_back
#define INF 0x3f3f3f3f
#define max(a, b) (a>b?a:b)
#define min(a, b) (a<b?a:b)


const double eps = 1e-8;
const int maxn = 1e6 + 10;
const ll MOD = 998244353;
const int mlog=20;

int sgn(double a) { return a < -eps ? -1 : a < eps ? 0 : 1; }

using namespace std;


ll sum[maxn];
int main() {
    ll a,b,c,d;
    ll ans = 0;
    cin >> a >> b >> c >> d;
    for (int i = a;i <= b;i++) {
        sum[i+b]++;
        sum[i+c+1]--;
    }
    for (int i = 1;i < maxn;i++)
        sum[i] += sum[i-1];
    for (int i = maxn-1;i >= 1;i--)
        sum[i] += sum[i+1];
    for (int i = c;i <= d;i++)
        ans += sum[i+1];
    cout << ans << endl;
    return 0;
}

 

posted @ 2020-08-13 10:45  _Ackerman  阅读(286)  评论(0编辑  收藏  举报