版权声明:欢迎转载 https://blog.csdn.net/l18339702017/article/details/83148473
题目来源: 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
按照题目的意思来模拟的话,代码应该是如下所示:
#pragma GCC optimize(2)
#include <bits/stdc++.h>
using namespace std;
#define clr(a) memset(a,0,sizeof(a))
#define line cout<<"-----------------"<<endl;
typedef long long ll;
const int maxn = 1e5+10;
const int MAXN = 1e6+10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9+7;
const int N = 1010;
ll n;
ll a[maxn];
ll fun(ll n){
ll sum = 0;
for(int i = 1; i <= n; i++){
for(int j = i + 1; j <= n; j++){
sum = sum + floor((a[i] + a[j]) / (a[i] * a[j]));
}
}
return sum;
}
int main(){
scanf("%lld", &n);
for(int i = 1; i <= n; i++){
scanf("%lld", &a[i]);
}
printf("%lld\n", fun(n));
return 0;
}
毫无疑问,肯定超时。我们再来重新思考一下这道题目。
对于两个数 x , y. floor((x + y) / (x * y)) 只可能有三种情况。0 、 1 、 2
当
x == 1 y == 1 的时候结果为2
x == 1 y == R 的时候结果为1
x == 2 y == 2 的时候结果为2
分别统计1 和 2 出现的次数 统计其对结果的贡献
#pragma GCC optimize(2)
#include <bits/stdc++.h>
using namespace std;
#define clr(a) memset(a,0,sizeof(a))
#define line cout<<"-----------------"<<endl;
typedef long long ll;
const int maxn = 1e5+10;
const int MAXN = 1e6+10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9+7;
const int N = 1010;
int n;
int a[maxn];
int main(){
scanf("%d", &n);
int num1 = 0, num2 = 0;
for(int i = 1; i <= n; i++){
scanf("%d", &a[i]);
if(a[i] == 1) num1 ++;
else if(a[i] == 2) num2 ++;
}
ll ans = 0;
ans += num2 * (num2 - 1) / 2;
ans += num1 * (n - 1);
cout << ans << endl;
return 0;
}