E
E
Elnurhan2020-05-22 12:00:24
C++ / C#
Elnurhan, 2020-05-22 12:00:24

What is wrong with the code - the RE flag?

There is a task: the file "input.txt" is fed to the input. The first line of this file contains the number k, the second line contains a sequence of numbers written with a space, numbers in the range 0 < n < 99999999. If the sequence contains two numbers whose sum is equal to k, then write to the file "output.txt" 1, otherwise - 0.

#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>

using namespace std;


int main()
{
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  unsigned int k, num, ind=0, mxN=2e6;
  
  unsigned int arr[mxN];
 
  ifstream in("input.txt");
  ofstream out("output.txt");

  in >> k;

  while (in >> num)
  {
    arr[ind] = num;
    ++ind;
  }
  if (!k || !ind) return 0;
  // 2 pointers
  sort(arr, arr+ind);
  int l = 0;
  int r = ind - 1;
  while (l != r)
  {
    if (arr[l] + arr[r] < k) 
    {
      ++l;
    }
    else if (arr[l] + arr[r] > k)
    {
      --r;
    }
    else {
      out << "1";
      out.close();
      return 0;
    }
  }

  out << "0";
  out.close();
  return 0;
}

Wrote this solution. It is working, but on one of the tests it crashes with the RE flag. With what it can be connected?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Zhilin, 2020-05-22
@Anton3

unsigned int arr[mxN];
Shield? A huge array on the stack, and even a variable size? This is anything but code that conforms to the C++ standard. Vector must be used.
Upd: Here you need to use unordered_set. Count numbers into it, then walk through it and see if there is an opposite number.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question