q5a.cpp 2.4 KB

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