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:
- #include<bits/stdc++.h>
- using namespace std;
- #define SET(a) memset(a,-1,sizeof(a))
- #define CLR(a) memset(a,0,sizeof(a))
- #define PI acos(-1.0)
- #define MOD 1000000007
- #define MX 100010
- int diff[55], n;
- void mov(int idx)
- {
- for(int i=0; i<n; i++)
- if(i==idx) diff[i]++;
- else diff[i]--;
- return;
- }
- bool allZero()
- {
- for(int i=0; i<n; i++)
- if(diff[i]!=0) return false;
- return true;
- }
- int main()
- {
- int tc,kk=1, h[55], d[55], cnt;
- cin>>tc;
- while(tc--)
- {
- cin>>n;
- for(int i=0; i<n; i++) cin>>h[i];
- for(int i=0; i<n; i++) cin>>d[i];
- for(int i=0; i<n; i++) diff[i]=d[i]-h[i];
- cnt=0;
- bool chk=false;
- if(n==1)
- {
- if(diff[0]>0) cout<<-1<<endl;
- else cout<<abs(diff[0])<<endl;
- }
- else if(n==2)
- {
- if(diff[0]+diff[1]==0) cout<<abs(diff[0])<<endl;
- else cout<<-1<<endl;
- }
- else
- {
- while(1)
- {
- int sum=0, mn=1e9, idx;
- for(int i=0; i<n; i++)
- {
- sum+=diff[i];
- if(diff[i]<mn)
- {
- mn=diff[i];
- idx=i;
- }
- }
- if(sum<0)
- {
- chk=true;
- break;
- }
- if(sum==0)
- {
- if(allZero())
- break;
- }
- cnt++;
- mov(idx);
- }
- if(chk) cout<<-1<<endl;
- else cout<<cnt<<endl;
- }
- }
- return 0;
- }
No comments:
Post a Comment