Topics

Chef is stuck in the wavey world of polynomials. You are given all roots of a polynomial . The roots are pairwise distinct integers, but they are not given in any particular order.

To help Chef escape, you should answer queries (numbered through ). For each valid , in the -th query, you are given an integer and you have to determine whether is positive, negative or .

Idea

Observe that the sign of depends on the number of factors that are negative. Ofcourse, if is equal to any of the roots , then . Otherwise, we can determine the sign by counting how many roots are greater than (since for roots , the diff is +ve and product of +ve nums is +ve). If this count is even, is positive; if it’s odd, is negative. To efficiently find the number of roots greater than , we can sort the roots and use binary search (or partition_point in c++) to find the position of in the sorted array.

Time Complexity: , where is the number of roots and is the number of queries. Sorting takes time, and each query involves a binary search taking time.
Space Complexity: (no extra space apart from storing array).

Code

void solve() {
  int n, q;
  cin >> n >> q;
  vector<int> arr(n);
  for (int i = 0; i < n; ++i) {
    cin >> arr[i];
  }
  sort(all(arr));
 
  int k;
  while (q--) {
    cin >> k;
 
    auto it = partition_point(all(arr), [&](int aj) { return aj <= k; });
    if (it != arr.begin() and *(it - 1) == k) {
      cout << 0 << '\n';
      continue;
    }
    int count_larger = distance(it, arr.end());
    if (count_larger % 2 == 0) {
      cout << "POSITIVE" << '\n';
    } else {
      cout << "NEGATIVE" << '\n';
    }
  }
}