Official

E - Lucky Numbers Editorial by en_translator


When one of the elements of a good sequence \(A\) is known, the entire \(A\) is uniquely determined. For example, if \(A_1\) equals \(Z\),

  • by the condition \(A_1 + A_2 = S_1\), \(A_ 2 = S_1 - Z\);
  • by the condition \(A_2 + A_3 = S_2\), \(A_ 3 = S_2 - A_2 = S_2 - S_1 + Z\);
  • by the condition \(A_3 + A_4 = S_3\), \(A_ 4 = S_3 - A_3 = S_3 - S_2 + S_1 - Z\);
  • \(\cdots\)

As listed above, the values of \(A_2, A_3, \ldots, A_N\) are uniquely determined in this order. In general, let \(Z\) be \(A_1\), then for \(i = 1, 2, \ldots, N\), we can express \(A_i\) by

\[ A_i = (-1)^{i+1} Z + B_i. \]

Here, the sequence \(B = (B_1, B_2, \ldots, B_N)\) is defined by

\[ B_i = \begin{cases} S_i - B_{i-1} & \text{if}\,\,\, i \geq 2\\ 0 & \text{if}\,\,\, i = 1. \end{cases} \]

Therefore, this problem is now rephrased to “maximize the number of lucky numbers in the elements of \(A\) by choosing appropriate \(Z\).”

For any pair \((i, j)\) of \(i = 1, 2, \ldots, N\) and \(j = 1, 2, \ldots, M\), \(A_i\) coincides with the lucky number \(X_j\) if and only if

\[ A_i = (-1)^{i+1} Z+ B_i = X_j, \]

that is,

\[ Z = (-1)^{i+1} (X_j - B_i). \tag{1} \]

Therefore, for all pairs of \(i = 1, 2, \ldots, N\) and \(j = 1, 2, \ldots, M\), let us define

\[C_{1, 1}, C_{1, 2}, \ldots, C_{N, M} \tag{2}\]

calculated by

\[C_{i, j} := (-1)^{i+1} (X_j - B_i),\]

then we can let \(Z\) the most frequent value \(C'\) in (2) so that the occurrences of lucky numbers in the sequence \(A\) is maximized. Hence, the answer for this problem is equal to the number of occurrences of \(C^{\ast}\) in (2). We can find the number of its occurrences with an associative array in a total of \(\mathrm{O}(NM\log NM)\) time.

The following an example of an accepted code in C++ language.

#include <iostream>
#include <map>
using namespace std;
typedef long long ll;

ll n, m;
ll s[200005], x[15];
ll b[200005];

int main(void)
{
  cin >> n >> m;
  for(int i = 1; i <= n-1; i++) cin >> s[i];
  for(int i = 1; i <= m; i++) cin >> x[i];
  
  for(int i = 2; i <= n; i++) b[i] = s[i-1] - b[i-1];
  
  map<ll, ll> mp;
  for(int i = 1; i <= n; i++){
    for(int j = 1; j <= m; j++){
      ll c = x[j] - b[i];
      if(i % 2 == 0) c *= -1;
      mp[c]++;
    }
  }
  
  ll ans = 0;
  for(auto p : mp) ans = max(ans, p.second);
  cout << ans << endl;
  
  return 0;
}

posted:
last update: