HDU 3908

    顯然O(n^3)的算法會超時。正確的解法是首先計算出與每個數互質的數的個數以及與每個數不互質的數的個數,分別記入數組co[]和nco[]。這樣,假設一個三元組包含數字x(x,..,..)。那麼包含x且不符合題意的三元組個數是co[x]*nco[x]。比如一組數字2,3,4,5,7,8。對於數字2來說,與2互質的數字個數是3,不互質的數字個數是2。所以不滿足題意的三元組數目是2*3=6。(2,3,4),(2,3,8),(2,5,4),(2,5,8),(2,7,4),(2,7,8)。然而對於某個三元組來說,我們計算了兩次,比如(2,3,4)在數字2計算了一次,在數字4也計算了一次。所以結果要除以2。最後只需要將總的三元組數目減去不符合題意的三元組數目即可。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <memory.h>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <iostream>
#include <sstream>

using namespace std;

int gcd(int a, int b) {
    while (b) {
        int r = a % b;
        a = b;
        b = r;
    }
    return a;
}

int d[805], co[805], nco[805];

int main() {
    int t, n, i, j, sum;
    for (scanf("%d", &t); t--; ) {
        scanf("%d", &n);
        for (i = 0; i < n; i++)
            scanf("%d", &d[i]);
        memset(co, 0, 4 * n);
        memset(nco, 0, 4 * n);
        for (i = 0; i < n; i++) {
            for (j = i + 1; j < n; j++) {
                if (gcd(d[i], d[j]) == 1)
                    co[i]++, co[j]++;
                else
                    nco[i]++, nco[j]++;
            }
        }
        sum = 0;
        for (i = 0; i < n; i++)
            sum += co[i] * nco[i];
        printf("%d\n", n * (n - 1) * (n - 2) / 6 - sum / 2);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章