DOBRI

伟伟有一个包含 N 个整数的序列 A ( 不要和前一题的序列混淆了)
。伟伟与众不同,
别人喜欢 2,她却喜欢 3, 当序列中的第 i 个元素等于位置在 i 前面的三个元素的和(一个元
素在”和”中用多次)
,那么第 i 个元素就称为幸福数。那么这个序列中包含多少个幸福元素?
输入格式:
输入文件的第一行包含一个整数 N (1<=N<=5000), 表示序列 A 的长度。
输入文件的第二行包含 N 个用空格隔开的整数,表示序列 A (-100000<=Ai<=100000).
输出格式:
输出文件仅一行,输出这个序列中包含多少个幸福元素。
数据范围:
40%的数据,N<=50
70%的数据,N<=500。

题解:

A naive solution, trying all possible combinations of three elements for
every i, is too slow. Its complexity is O(N 4 ) and is worth 40% points.
Since the values in the array are small, we can have an array P which tells
us if there exists a certain value in the array before the current position i.
More precisely, P[x] = 1 if there is a value x in the array A before the
position i, else P[x] = 0. Using that, we can improve our starting
solution. Instead of trying every possible combination of three elements,
we try every possible pair of positions (j, k) less than i and ask if there is
a value A[i] - A[j] - A[k] in the array before i. We have that information
in the array P on the position A[i] - A[j] - A[k]. After processing the
position i, we set P[A[i]] = 1. We have thus achieved the complexity of
O(N 3 ) and 70% points.
For 100% points we need an algorithm with a time complexity of O(N 2 ).
Instead of asking if there is a value A[i] - A[j] - A[k] for each pair (j, k)
in the array before i, we can ask for every position j if there is a pair of
values before i such that their sum is equal to A[i] - A[j]. We can again
use the array P to answer that, because the sum of two small numbers is
also a small number. After processing the position i, for every pair (i, j)
with j ≤ i we set P[A[i] + A[j]] = 1. Using this optimization we get a
solution that is fast enough and that achieves full points.
Notice that the space complexity of the algorithm is O(max A i ), but if
there were larger numbers in the task, we could use a balanaced tree
instead of the array P. In C++ we can use set and map. We would thus
get a solution of a space complexity O(N) and time complexity O(N 2 log
N) which was worth 70% points in this task.

(开玩笑的)

找出x<=y<=z且a[x]+a[y]+a[z]=a[i]的(x,y,z)对数
vis[sum]=1表示a[i]之前存在两个元素,它们之和为sum
问题转化为,枚举z,问vis[a[i]-a[z]]是否为1
注意下标不要越界
时间复杂度O(n^2)

猜你喜欢

转载自www.cnblogs.com/000226wrp/p/11336233.html