1305 Pairwise Sum and Divide

时间:2023-03-09 17:01:39
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

题目链接:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1305

分析:看大佬的分析,才知道,本人一直超时!不说了,统计1的个数和2的个数,有多少1就加一个1,有多少个2就是n*(n-1)/2!
下面给出AC代码:
 #include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
int a[];
while(scanf("%d",&n)!=EOF)
{
for(int i=;i<=n;i++)
scanf("%d",&a[i]);
sort(a+,a++n);
int c1=,c2=,c3=;
for(int i=;i<=n;i++)
{
if(a[i]==)
c1++;
else if(a[i]==)
c2++;
else c3++;
}
int ans=c1*(c1+c2+c3-)+c2*(c2-)/;
printf("%d\n",ans);
}
return ;
}