fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5. #define print(a) for(auto x : a) cout << x << " "; cout << endl
  6.  
  7.  
  8. const int M = 1000000007;
  9. const int N = 3e5+9;
  10. const int INF = 2e9+1;
  11. const int LINF = 2000000000000000001;
  12.  
  13. inline int power(int a, int b, int mod=M) {
  14. int x = 1;
  15. a %= mod;
  16. while (b) {
  17. if (b & 1) x = (x * a) % mod;
  18. a = (a * a) % mod;
  19. b >>= 1;
  20. }
  21. return x;
  22. }
  23.  
  24.  
  25. //_ ***************************** START Below *******************************
  26.  
  27.  
  28.  
  29.  
  30. vector<int> a;
  31.  
  32. int consistency(int n, int t){
  33.  
  34. sort(begin(a), end(a));
  35.  
  36. int minDif = INF;
  37. int ans = -1;
  38.  
  39. for(int i=0; i<=n-3; i++){
  40. int s = i+1;
  41. int e = n-1;
  42.  
  43. while(s<e){
  44. int sum = a[i] + a[s] + a[e];
  45. int dif = abs(t - sum);
  46.  
  47. if(dif < minDif){
  48. minDif = dif;
  49. ans = sum;
  50. }
  51.  
  52. if(sum >= t){
  53. e--;
  54. }
  55. else{
  56. s++;
  57. }
  58. }
  59. }
  60.  
  61. return ans;
  62.  
  63. }
  64.  
  65.  
  66.  
  67.  
  68.  
  69.  
  70.  
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
  78.  
  79. int practice(int n){
  80.  
  81.  
  82. return 0;
  83. }
  84.  
  85.  
  86.  
  87.  
  88.  
  89. void solve() {
  90.  
  91. int n, t;
  92. cin>> n >> t;
  93.  
  94. a.resize(n);
  95. for(int i=0; i<n; i++) cin >> a[i];
  96.  
  97. cout << consistency(n, t) << endl;
  98.  
  99.  
  100. }
  101.  
  102.  
  103.  
  104.  
  105.  
  106. int32_t main() {
  107. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  108.  
  109. int t = 1;
  110. // cin >> t;
  111. while (t--) {
  112. solve();
  113. }
  114.  
  115. return 0;
  116. }
Success #stdin #stdout 0s 5312KB
stdin
4 1
-4 -1 1 2
stdout
2