q5.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include <iostream>
  2. #include <cstdlib>
  3. #include <string>
  4. /*int n;
  5. int twon = 2 * n;
  6. int * a;
  7. int * b;
  8. int * sums = malloc(2 * sizeof(b));
  9. int pos = 0;
  10. for (int i = 0; i < twon; i++)
  11. {
  12. for (int j = (i + 1); j < twon; j++, pos++)
  13. {
  14. sums[pos] = b[i] + b[j];
  15. }
  16. }
  17. sort c;
  18. for (int i = 0; i < twon; i++)
  19. {
  20. for (int j = (i + 1); j < twon; j++, pos++)
  21. {
  22. if sums.search(a[i] + a[j]) return true;
  23. }
  24. }
  25. return false;
  26. ================*/
  27. int n;
  28. std::cin >> n; // get the length of the array we are manipulating
  29. int * a = malloc(n * sizeof(int));
  30. int * b = malloc(n * sizeof(int));
  31. for (int i = 0; i < n; ++i)
  32. {
  33. // get each line which is 2 ints, put into A and B
  34. std::string input;
  35. std::getline(std::cin, input);
  36. std::stringstream nums(input);
  37. nums >> a[i];
  38. nums >> b[i];
  39. }
  40. /*
  41. int clen = 2 * n;
  42. int * C = malloc(clen * sizeof(int)); // to hold the list of possible sums
  43. int tempcount = 0;
  44. for (int i = 0; i < n; i++)
  45. {
  46. for (int j = (i + 1); j < n; ++j, ++tempcount)
  47. {
  48. C[tempcount] = (B[i] + B[j]);
  49. C[clen - tempcount - 1] = (A[i] + A[j]);
  50. }
  51. } // n squared
  52. sort(C, C + clen); // n^2 log n squared == n^2 log n */
  53. int clen = (n * (n - 1)) / 2; // total possible sums in an array of length n
  54. int * c = malloc(clen * sizeof(int));
  55. int tempcount = 0;
  56. // Store within c the possible sums inside b
  57. for (int i = 0; i < n; ++i)
  58. {
  59. for (int j = (i + 1); j < n; ++j, ++tempcount)
  60. {
  61. c[tempcount] = b[i] + b[j];
  62. }
  63. }
  64. // sort c, with time complexity n squared log (n squared), which reduces to n squared log n
  65. std::sort(c, c + clen);
  66. // for reach sum in a, see if it is in c. n squared checks of log (n squared), or n squared log n
  67. for (int i = 0; i < clen; ++i)
  68. {
  69. for (int j = (i + 1); j < n; ++j)
  70. {
  71. if (std::binary_search(c, c + clen), (a[i] + a[j]))
  72. {
  73. free(a); free (b); free(c);
  74. cout << 1 << endl;
  75. return true;
  76. }
  77. }
  78. }
  79. free(a); free(b); free(c);
  80. cout << 0 << endl;
  81. return false;