q5a.cpp 2.5 KB

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