首页 > 代码库 > Hackrank Equal DP
Hackrank Equal DP
Christy is interning at HackerRank. One day she has to distribute some chocolates to her colleagues. She is biased towards her friends and may have distributed the chocolates unequally. One of the program managers gets to know this and orders Christy to make sure everyone gets equal number of chocolates.
But to make things difficult for the intern, she is ordered to equalize the number of chocolates for every colleague in the following manner,
For every operation, she can choose one of her colleagues and can do one of the three things.
- She can give one chocolate to every colleague other than chosen one.
- She can give two chocolates to every colleague other than chosen one.
- She can give five chocolates to every colleague other than chosen one.
Calculate minimum number of such operations needed to ensure that every colleague has the same number of chocolates.
Input Format
First line contains an integer denoting the number of testcases. testcases follow.
Each testcase has lines. First line of each testcase contains an integer denoting the number of colleagues. Second line contains N space separated integers denoting the current number of chocolates each colleague has.
Constraints
Number of initial chocolates each colleague has <
Output Format
lines, each containing the minimum number of operations needed to make sure all colleagues have the same number of chocolates.
Sample Input
142 2 3 7
Sample Output
2
Explanation
1st operation: Christy increases all elements by 1 except 3rd one
2 2 3 7 -> 3 3 3 8
2nd operation: Christy increases all element by 5 except last one
3 3 3 8 -> 8 8 8 8
#include<bits/stdc++.h>using namespace std;#pragma comment(linker, "/STACK:102400000,102400000")#define ls i<<1#define rs ls | 1#define mid ((ll+rr)>>1)#define pii pair<int,int>#define MP make_pairtypedef long long LL;const long long INF = 1e18+1LL;const double Pi = acos(-1.0);const int N = 6e3+10, M = 1e3+20, mod = 2017,inf = 2e9;int dp[N][N],a[10005];int main() { for(int i = 0;i <= 6000; ++i) for(int j = 0; j <= 6000; ++j) dp[i][j] = inf; for(int i = 0; i <= 6000; ++i) { dp[i][i] = 0; for(int j = 0; j < i; ++j) { if(i-1>=j) dp[i][j] = min(dp[i-1][j]+1,dp[i][j]); if(i-5>=j) dp[i][j] = min(dp[i-5][j]+1,dp[i][j]); if(i-2>=j) dp[i][j] = min(dp[i-2][j]+1,dp[i][j]); } } int T,n; scanf("%d",&T); while(T--) { scanf("%d",&n); int mi = inf; for(int i = 1; i <= n; ++i) scanf("%d",&a[i]),mi = min(mi,a[i]+1000); int ans = 0; for(int i = 1; i <= n; ++i) { ans += dp[a[i]+1000][mi]; } for(int i = 0; i <= mi; ++i) { int sum = 0 ; for(int j = 1; j <= n; ++j) { sum += dp[a[j]+1000][i]; } ans = min(ans,sum); } printf("%d\n",ans); } return 0;}
Hackrank Equal DP