ACdream OJ 1140 Counting Triangles

  给出N条边,问这些边能组成多少个不同的三角形,每条边的长度是不同的。首先我们先

将边长按照升序排序,然后枚举两条短的边,看最长边有多少种可能,累加。

#include<cstdio>

#include<cstring>

#include<cstdlib>

#include<iostream>

#include<algorithm>

using namespace std;



const int MAXN = 2012;

int T, N;

int a[MAXN];



int b_s( int len)

{

    int left = 0, right = N - 1;

    while( left < right) {

        int mid = ( left + right + 1) >> 1;

        if( a[mid] >= len)

            right = mid - 1;



        else

            left = mid;

    }

    return left;

}



int cal()

{

    int cnt = 0;

    for( int i = 0; i < N; i ++)

        for( int j = i + 1; j < N; j ++) {

            int len = a[j] + a[i];

            int pos = b_s( len);

            cnt += (pos - j);

        }

    return cnt;

}



int main()

{

    scanf( "%d", &T);

    for( int cas = 1; cas <= T; cas ++)

    {

        scanf( "%d", &N);

        for( int i = 0; i < N; i ++)

            scanf( "%d", &a[i]);

        sort( a, a + N);

        int ans = cal();

        printf( "Case %d: %d\n", cas, ans);

    }

    return 0;

}

 

 

你可能感兴趣的:(count)