【題解】英雄會第二屆線上程式設計大賽·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 //提示:自動閱卷結束唯一標識,請勿刪除或增加。