51Nod1305 Pairwise Sum and Divide

51Nod1305 Pairwise Sum and Divide

题意

有这样一段程序,fun会对整数数组A进行求值,其中Floor表示向下取整:

fun(A)
sum = 0
for i = 1 to A.length
for j = i+1 to A.length
sum = sum + Floor((A[i]+A[j])/(A[i]*A[j]))
return sum

给出数组A,由你来计算fun(A)的结果。例如:A = {1, 4, 1},fun(A) = [5/4] + [2/1] + [5/4] = 1 + 2 + 1 = 4。

题解

(a + b) / (a * b) 等价于 1 / b + 1 / a.

a == 1 a == 2 a 为其他值
b == 1 2 1 1
b == 2 1 1 0
b 为其他值 1 0 0

所以答案为 C(2, cnt1) * 2 + C(cnt2 * 2) + C(cnt1, others + cnt2)

AC代码

#include <cstdio>
#include <regex>
using namespace std;
const int ARRSIZE = 100100;
long long arr[ARRSIZE];
int main() {
    int nNum; scanf("%I64d", &nNum);
    long long cnt1 = 0, cnt2 = 0, others = 0;
    for(int i = 0; i < nNum; i++) {
        long long num; scanf("%I64d", &num);
        if(num == 1) cnt1++;
        else if(num == 2) cnt2++;
        else others++;
    }
    printf("%I64d", cnt1 * (cnt1 - 1) + cnt1 * (others + cnt2) + cnt2 * (cnt2 - 1) / 2);
    return 0;
}

posted @ 2018-04-18 20:44  1pha  阅读(93)  评论(0编辑  收藏  举报