1305 Pairwise Sum and Divide

1305 Pairwise Sum and Divide

题目来源: HackerRank
基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题
收藏
关注
有这样一段程序,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和2就可以了,仔细想下.
 1 #include <bits/stdc++.h>
 2 #define N 100005
 3 using namespace std;
 4 int k[N];
 5 int main(){
 6   int n;
 7   scanf("%d",&n);
 8   long long int sum=0;
 9   int cnt=0,ans=0;
10   for(int i=0;i<n;i++)
11     scanf("%d",&k[i]);
12   for(int i=0;i<n;i++){
13     if(k[i]==1)
14       cnt++;
15     if(k[i]==2)
16       ans++;
17     }
18   sum=cnt*(cnt-1)+cnt*(n-cnt)+ans*(ans-1)/2;
19   printf("%lld
", sum);
20   return 0;
21 }
原文地址:https://www.cnblogs.com/zllwxm123/p/7374756.html