1. 程式人生 > >[51nod] 1305 Pairwise Sum and Divide 數學

[51nod] 1305 Pairwise Sum and Divide 數學

size ont col 取整 include 次數 lld output ext

有這樣一段程序,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。 Input
第1行:1個數N,表示數組A的長度(1 <= N <= 100000)。
第2 - N + 1行:每行1個數A[i](1 <= A[i] <= 10^9)。
Output
輸出fun(A)的計算結果。
Input示例
3
1 4 1
Output示例
4

按照定義做會超時,也不會那麽簡單的 ,需要找一定的規律
(1+1)/1 = 2 1 < (1+n)/n < 2 n > 1 取整後為1
(2+2)/4 = 1
事實上 (a + b)/ab = 1/a + 1/b a>2且b>2時 不等式(a+b)/ab < 1 a,b不全為2時等號成立
取整後為0 , 所以只用查找1和2,以及>=2的個數即可
公式:sum = 2(N1-1)*N1/2 + N1*(∑Nk k>=2) + N2*(N2-1)/2
註意乘的次數
#include <stdio.h>

#define
LL long long int N, n; int one, two, other; int main() { //freopen("1.txt", "r", stdin); scanf("%d", &N); for (int i = 0; i < N; i++) { scanf("%d", &n); if (n == 1) one++; if (n == 2) two++; if (n >= 2) other
++; } LL sum = 0; sum += (one-1)*one + one*other + ( (two*(two-1))>>1 ); printf("%lld\n", sum); return 0; }

 

[51nod] 1305 Pairwise Sum and Divide 數學