Codeforces Round 858 (Div. 2) 1806 C - Sequence Maste Solution


 

 Problem Link :  https://codeforces.com/contest/1806/problem/C

Solution in C++:

  1. /// La ilaha illellahu muhammadur rasulullah
  2. ///******Bismillahir-Rahmanir-Rahim******///
  3. /// Abul Hasnat Tonmoy
  4. /// Department of CSE,23rd batch
  5. /// Islamic University,Bangladesh
  6. ///**********ALLAH IS ALMIGHTY************///
  7. #include <bits/stdc++.h>
  8. using namespace std;
  9. int32_t main() {
  10. ios_base::sync_with_stdio(0);
  11. cin.tie(0);
  12. int test;
  13. cin >> test;
  14. while (test--) {
  15. long long n;
  16. cin >> n;
  17. long long m = 2 * n;
  18. long long temp = 0, ar[m + 9], ans = 0;
  19. for (int i = 1; i <= m; i++) {
  20. cin >> ar[i];
  21. ans += abs(ar[i]);
  22. }
  23. sort(ar + 1, ar + m + 1);
  24. if (m == 2) {
  25. ans = min(ans, abs(ar[1] - ar[2]));
  26. cout << ans << endl;
  27. } else if (m == 4) {
  28. temp = 0;
  29. for (int i = 1; i <= m; i++) {
  30. temp += abs(2 - ar[i]);
  31. }
  32. ans = min(temp, ans);
  33. temp = 0;
  34. for (int i = 1; i < m; i++) {
  35. temp += abs(-1 - ar[i]);
  36. }
  37. temp += abs(2 - ar[m]);
  38. ans = min(temp, ans);
  39. cout << ans << endl;
  40. } else if (m % 4 == 0) {
  41. std::vector<int> v;
  42. for (int i = 1; i < m; i++) {
  43. v.push_back(-1);
  44. }
  45. v.push_back(n);
  46. temp = 0;
  47. for (int i = 1; i <= m; i++) {
  48. temp += abs(v[i - 1] - ar[i]);
  49. }
  50. ans = min(temp, ans);
  51. cout << ans << endl;
  52. } else {
  53. cout << ans << endl;
  54. }
  55. }
  56. return 0;
  57. }

No comments

Most View Post

Recent post

Codeforces Round 971 (Div. 4) 2009C. The Legend of Freya the Frog Solution

  Problem Link    https://codeforces.com/contest/2009/problem/C S olution in C++: /// Author : AH_Tonmoy #include < bits / stdc ++. h &g...

Powered by Blogger.