a1q5.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <cstdlib>
  4. #include <string>
  5. #include <sstream>
  6. using namespace std;
  7. int main()
  8. {
  9. string en;
  10. int n;
  11. getline(cin, en);
  12. stringstream cast(en);
  13. cast >> n; // get the length of the array we are manipulating
  14. int * a = (int *) malloc(n * sizeof(int));
  15. int * b = (int *) malloc(n * sizeof(int));
  16. for (int i = 0; i < n; ++i)
  17. {
  18. // get each line which is 2 ints, put into A and B
  19. string input;
  20. getline(cin, input);
  21. stringstream nums(input);
  22. nums >> a[i];
  23. nums >> b[i];
  24. }
  25. int clen = (n * (n + 1)) / 2; // total possible sums in an array of length n
  26. int * c = (int *) malloc(clen * sizeof(int));
  27. int tempcount = 0;
  28. // Store within c the possible sums inside b
  29. for (int i = 0; i < n; ++i)
  30. {
  31. for (int j = i; j < n; ++j, ++tempcount)
  32. {
  33. c[tempcount] = b[i] + b[j];
  34. }
  35. }
  36. // sort c, with time complexity n squared log (n squared), which reduces to n squared log n
  37. sort(c, c + clen);
  38. // for reach sum in a, see if it is in c. n squared checks of log (n squared), or n squared log n
  39. for (int i = 0; i < clen; ++i)
  40. {
  41. for (int j = i; j < n; ++j)
  42. {
  43. if (binary_search(c, (c + clen), (a[i] + a[j])))
  44. {
  45. free(a); free (b); free(c);
  46. cout << "TRUE" << endl;
  47. return 0;
  48. }
  49. }
  50. }
  51. free(a); free(b); free(c);
  52. cout << "FALSE" << endl;
  53. return 0;
  54. }