Problem Analysis:
It is actually a basic Bisection problem , as we can see here we can not actually find a formula for the camp distance but what we can do is for a certain camp distance we can check how many nights or how many nights we must stay in a camp. and if that's less than k than we are good but else we need to check for smaller distances.
here isp() function just validates for any certain distance is it possible to do it less than or equal k nights or not. and in the main function that bisection just puts the data from the function to Isp() to search for a better result.
If for certain "l" Isp(l) returns true than we check if there is another l' which is l'<l and still isp(l') returns true or not.
else we increse I and check for the isp(I) for which it is true result again. The printing part is a little tricky But can be done.
Here goes the code:
- #include <bits/stdc++.h>
- using namespace std;
- vector<int>v;
- int k;
- bool isp(int l){
- int co = 0;
- int sum =v[0];
- for(int i = 1; i <v.size(); i++){
- if(v[i]>l) return false;
- else if(sum+v[i]<=l){
- sum+= v[i];
- }
- else{
- sum = v[i];
- co++;
- }
- }
- if(co<=k) return true;
- return false;
- }
- void prt(int l){
- int sum= 0;
- int co = 0;
- for(int i = 0; i <v.size(); i++){
- sum+= v[i];
- if(sum>l){
- printf("%d\n", sum-v[i]);
- sum = v[i];
- co++;
- }
- if(k-co+1>=v.size()-i){
- printf("%d\n", sum);
- for(int j = i+1; j <v.size(); j++) printf("%d\n", v[j]);
- break;
- }
- }
- }
- int main(){
- int ts;
- scanf("%d", &ts);
- for(int p = 1; p <= ts; p++){
- v.clear();
- int n,low = INT_MIN, high = 0, mid = 0, ans;
- scanf("%d%d", &n, &k);
- for(int i = 0; i <=n; i++){
- int a;
- scanf("%d", &a);
- high+= a;
- v.push_back(a);
- low = max(low, a);
- }
- while(high-low>2){
- mid = (low+high)/2;
- if(isp(mid)) high = mid;
- else low = mid;
- }
- for(int i = high; i >= low; i--) if(isp(i)) ans = i;
- printf("Case %d: %d\n",p, ans);
- prt(ans);
- }
- return 0;
- }
It really helped me, Thanks.
ReplyDeleteYour coding style is very helpful and easy to understand unlike others.
Happy to help :)
Deleteit would be v[j] in line 33
ReplyDeleteYes, that's right.
DeleteUpdated. Thanks
DeleteThis comment has been removed by the author.
ReplyDelete