给定一个数组。程序应该找到所有对的总和可以除以7.我编写这段代码,但代码没有通过所有测试
#include <iostream>
using namespace std;
int m[7];
int main() {
int n, k = 0;
cin>>n;
long long a;
for(int i = 0; i < n; i++) {
cin>>a;
a %= 7;
if(m[(7 - a) % 7] > 0) {
k += m[(7 - a) % 7];
}
m[a]++;
}
cout<<k;
return 0;
}
答案 0 :(得分:1)
我只是使用散列来存储余数的频率除以7:
int count7Divisibiles(int arr[], int n)
{
// Create a frequency array to count
// occurrences of all remainders when
// divided by 7
int freq[7] = {0, 0, 0, 0, 0, 0, 0};
// Count occurrences of all remainders
for (int i = 0; i < n; i++)
++freq[arr[i] % 7];
// If both pairs are divisible by '7'
int ans = freq[0] * (freq[0] - 1) / 2;
// If one of them is equal
// to 1 modulo 7 and the
// other is equal to 3
// modulo 7
ans += freq[1] * freq[6];
// for 2%7 and 5%7
ans += freq[2] * freq[5];
//for 3%7 and 4%7
ans += freq[3] * freq[4];
return ans;
}
n*(n-1)/2
count(a%7)*count((7-a)%7)