Monday, 14 October 2013

CodeChef October Challenge 2013 Editorial [Little Elephant and Bamboo]

Problem: Little Elephant and Bamboo
You are given N bamboo of different height Hi. this is the current height of the bamboos. Next you will be given N bamboo of required height Di
A single operation means decreasing height of a bamboo by 1 and increasing all others by 1. your task to minimize the operation to make all current height to required height. If it's impossible, print -1.

Solution Idea: Brute Force.
first of all, make another array, diff[] to calculate differences of required and current array.
diff[i]=d[i]-h[i];
now operation reversed, an operation means increasing height of a bamboo by 1, and decreasing all other by 1. your target is to make all diff[] to 0.
note that, you are increasing only one height and decreasing all other. so after each operation summation of diff[] array will decrease.
so, if somehow summation of diff array goes to negative there is no solution exists.
what element you will increase to balance? simple, the minimum one. make a function for an operation. if sum of diff[] become to 0 you have to check whether all diff[] are 0 or not. if all are 0 the number of operation you made is the answer.

Note: Special check for N=1 & N=2.

Code:
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define SET(a) memset(a,-1,sizeof(a))
  5. #define CLR(a) memset(a,0,sizeof(a))
  6. #define PI acos(-1.0)
  7. #define MOD 1000000007
  8. #define MX 100010

  9. int diff[55], n;
  10. void mov(int idx)
  11. {
  12. for(int i=0; i<n; i++)
  13. if(i==idx) diff[i]++;
  14. else diff[i]--;
  15. return;
  16. }
  17.  
  18. bool allZero()
  19. {
  20. for(int i=0; i<n; i++)
  21. if(diff[i]!=0) return false;
  22. return true;
  23. }
  24.  
  25. int main()
  26. {
  27. int tc,kk=1, h[55], d[55], cnt;
  28. cin>>tc;
  29. while(tc--)
  30. {
  31. cin>>n;
  32. for(int i=0; i<n; i++) cin>>h[i];
  33. for(int i=0; i<n; i++) cin>>d[i];
  34. for(int i=0; i<n; i++) diff[i]=d[i]-h[i];
  35. cnt=0;
  36. bool chk=false;
  37. if(n==1)
  38. {
  39. if(diff[0]>0) cout<<-1<<endl;
  40. else cout<<abs(diff[0])<<endl;
  41. }
  42. else if(n==2)
  43. {
  44. if(diff[0]+diff[1]==0) cout<<abs(diff[0])<<endl;
  45. else cout<<-1<<endl;
  46. }
  47. else
  48. {
  49. while(1)
  50. {
  51. int sum=0, mn=1e9, idx;
  52. for(int i=0; i<n; i++)
  53. {
  54. sum+=diff[i];
  55. if(diff[i]<mn)
  56. {
  57. mn=diff[i];
  58. idx=i;
  59. }
  60. }
  61. if(sum<0)
  62. {
  63. chk=true;
  64. break;
  65. }
  66. if(sum==0)
  67. {
  68. if(allZero())
  69. break;
  70. }
  71. cnt++;
  72. mov(idx);
  73. }
  74. if(chk) cout<<-1<<endl;
  75. else cout<<cnt<<endl;
  76. }
  77. }
  78. return 0;
  79. }

No comments:

Post a Comment