【题解】英雄会第二届在线编程大赛·CSDN现场决赛:三元组的数量

题目链接:

http://hero.csdn.net/Question/Details?ID=222&ExamID=217题目详情

{5 3 1}和{7 5 3}是2组不同的等差三元组,除了等差的性质之外,还有个奇妙的地方在于:5^2 – 3^2 – 1^2 = 7^2 – 5^2 – 3^2 = N = 15。

{19 15 11}同{7 5 3}这对三元组也存在同样的性质:19^2 – 15^2 – 11^2 = 7^2 – 5^2 – 3^2 = N = 15。

这种成对的三元组还有很多。当N = 15时,有3对,分别是{5 3 1}和{7 5 3},{5 3 1}和{19 15 11},{7 5 3}和{19 15 11}。


现给出一个区间 [a,b]求a <= N <= b 范围内,共有多少对这样的三元组。(1 <= a <= b <= 5*10^6)

例如:a = 1,b = 30,输出:4。(注:共有4对,{5 3 1}和{7 5 3},{5 3 1}和{19 15 11},{7 5 3}和{19 15 11},{34 27 20}和{12 9 6})

思路:

设中间的数字为x,间距为y,则3个数字为x+y, x, x-y,(x+y)^2 - x^2 - (x-y)^2 = 4xy-x^2 = x(4y-x)  (注意题目给的例子,隐含3个数字必须要都是正整数)

对于题目中给定的范围(1 <= a <= b <= 5*10^6),开辟等大小的数组,初始化为全0.

对于某个N,从1遍历到sqrt(N)可以得到他的所有约数,如果它的一组约数{a,b} 满足a = x, b = 4y-b,那么我们就在数组里面对应N的位置+1。等都算完了之后回头再统计一下每个数字对应的数组值为多少,用组合数C(数组中的值,2),全部相加就可以了。

代码:

#include <stdio.h>
#include <iostream>
#include <string>
#include <math.h>
using namespace std;

int g_array[1+5000000] = {0};
// x(4y-x) = N
int num2(int a, int b) {
    int ret = 0;
    memset(g_array, 0, sizeof(g_array));
    int max = (int)sqrt((double)b);
    for (int x = 1; x <= max; x++) {
        int n = a/x * x;
        if (n < a) n += x;
        for (; n <= b; n += x) {
            if (x*x > n) continue;
            if ((n/x + x)%4 == 0) {
                int y = (n/x + x) / 4;
                if( x > y) {
                    g_array[n]++;
                    //printf("(%d %d %d) = %d \n", x+y, x, x-y, n);
                }
                if (n/x > y && n != x*x) {
                    g_array[n]++;
                    //printf("(%d %d %d) = %d \n", n/x+y, n/x, n/x-y, n);
                }
            }
        }
    }
    for (int i = a; i <= b; i++) {
        if (g_array[i] > 1)
            ret += g_array[i]*(g_array[i]-1)/2;
    }
    return ret;
}

class Test {
public:
    static long Count (int   a,int   b)
    {
        return num2(a,b);
    }
};
//start 提示:自动阅卷起始唯一标识,请勿删除或增加。
int main()
{   
    cout<<Test::Count(1,30)<<endl;   
    cout<<Test::Count(1,500000)<<endl; 
    cout<<Test::Count(1,5000000)<<endl;   
} 
//end //提示:自动阅卷结束唯一标识,请勿删除或增加。


猜你喜欢

转载自blog.csdn.net/sun2043430/article/details/17732901