Problem Statement
One day, Bob the Coder was wondering whether abstract programming problems can have applications in practice. The next day, he was selected to be on a quiz show. He will win one million dollars if he answers the following question: Given a vector A with N elements and an int K, count the number of tuples (p, q, r) such that 0 <= p < q < r < N and A[p] * A[q] * A[r] is divisible by K. Please compute and return the answer to Bob’s question.
Definition
Class:
AnArray
Method:
solveProblem
Parameters:
vector , int
Returns:
int
Method signature:
int solveProblem(vector A, int K)
(be sure your method is public)
Limits
Time limit (s):
2.000
Memory limit (MB):
256
Stack limit (MB):
256
Constraints
A will contain between 3 and 2,000 elements, inclusive.
K will be between 1 and 1,000,000, inclusive.
Each element of A will be between 1 and 100,000,000, inclusive.
Examples
0)
{31, 1, 3, 7, 2, 5}
30
Returns: 1
The return value is 1 because there is exactly one valid tuple. The tuple is (2, 4, 5). It is valid because A[2] * A[4] * A[5] = 3 * 2 * 5 = 30.
1)
{4, 5, 2, 25}
100
Returns: 2
2)
{100000000, 100000000, 100000000}
1000000
Returns: 1
Note that the product A[p] * A[q] * A[r] doesn’t have to fit into a 64-bit integer variable.
3)
{269, 154, 94, 221, 171, 154, 50, 210, 258, 358, 121, 159, 8, 47, 290, 125, 291, 293, 338, 248, 295, 160, 268, 227, 99, 4, 273}
360
Returns: 114
4)
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
1
Returns: 220
This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.
My solution
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
class AnArray
{
public:
int solveProblem(vector <int>, int);
};
int AnArray::solveProblem(vector <int> A, int K)
{
int size = A.size();
vector<unsigned long long> B(size);
for (int i = 0; i < size; i++)
{
B[i] = A[i] % K;
}
unsigned int total = 0;
for (int i = 0; i < size - 2; i++)
{
//第一个数就能被K整除
if (B[i] % K == 0)
{
int n = size - (i + 1);
total += (n * (n - 1)) / 2;
continue;
}
for (int j = i + 1; j < size - 1; j++)
{
unsigned long long partial_product = (B[i] * B[j]) % K;
//前两个相乘就能被K整除
if (!partial_product)
{
total += size - (j + 1);
continue;
}
//三个相乘才能被K整除
for (int kk = j + 1; kk < size; kk++)
{
unsigned long long total_product = (partial_product * B[kk]) % K;
if (!total_product)
total++;
}
}
}
return total;
}