-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodility_L6(Sorting)_NumberOfDiscIntersections.cpp
85 lines (72 loc) · 1.3 KB
/
Codility_L6(Sorting)_NumberOfDiscIntersections.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <vector>
// correct but slow O(N*N) solution (75%)
int slowSolution(std::vector<int>& A) noexcept
{
if (A.size() < 2) return 0;
std::vector<long> S(A.size());
std::vector<long> E(A.size());
for (size_t i = 0; i != A.size(); ++i)
{
S[i] = static_cast<long>(i) - A[i];
E[i] = static_cast<long>(i) + A[i];
}
int sum = 0;
for (size_t i = 0; i != A.size() - 1; ++i)
{
for (size_t j = i + 1; j != A.size(); ++j)
{
if ((E[j] >= S[i] && E[j] <= E[i]) || (S[j] >= S[i] && S[j] <= E[i]))
{
++sum;
}
else if (S[j] < S[i] && E[j] > E[i])
{
++sum;
}
}
if (sum > 10000000)
{
return -1;
}
}
return sum;
}
int solution(std::vector<int>& A) noexcept
{
const int size = static_cast<int>(A.size());
std::vector<int> S(size);
std::vector<int> E(size);
// O(N)
for (int i = 0; i != size; ++i)
{
if (i < A[i])
{
++S.front();
}
else
{
++S[i - A[i]];
}
if (static_cast<long>(i) + A[i] >= size)
{
++E.back();
}
else
{
++E[i + A[i]];
}
}
int sum = 0;
int active = 0;
// O(N)
for (int i = 0; i != size; ++i)
{
sum += active * S[i] + (S[i] * (S[i] - 1)) / 2;
if (sum > 10000000)
{
return -1;
}
active += S[i] - E[i];
}
return sum;
}