Tuesday 2 April 2019

Spoj Problem ACMCEG2C - Pick the candies (C++)


  The problem link may be found here.
      Explanation:
  • Use Deque to keep track of elements of the variety of candies.
  • If i is greater that allowed variety of Candies pop the front element of the queue
  • Based of condition only keep the maximum element, pop everything thats smaller than the ith element

 1  #include<bits/stdc++.h>
 2  using namespace std;
 3  void sliding(vector<int>&v,int k){
 4  deque<int>q;
 5  vector<int>res;
 6  for(int i=0;i<v.size();i++){
 7      while(!q.empty() && i-q.front()>=k){
 8          q.pop_front();
 9      }
10      while(!q.empty() && v[q.back()]< v[i]){
11          q.pop_back();
12      }
13      q.push_back(i);
14      if(i>=k-1)res.push_back(v[q.front()]);
15  }
16  for(int i=0;i<res.size();i++){
17          cout<<res[i]<<" ";
18      }
19  }
20  int main(){
21  int t,n,k,m;
22 
23  scanf("%d",&t);
24  while(t--){
25      cin>>n>>k;
26       vector<int>v;
27       vector<int>ans;
28      for(int i=0;i<n;i++){
29          cin>>m;
30          v.push_back(m);
31      }
32      sliding(v,k);
33 
34  cout<<endl;
35  }
36 
37 
38  return 0;}

Wednesday 20 March 2019

UVA Problem 12207 - That is Your Queue (C++)

The problem link can be found here. It has been solved using deque data structure.
Code:

 1  #include<bits/stdc++.h>
 2  using namespace std;
 3  int main(){
 4      int cases =0;
 5  int p,c;
 6 
 7  while(cin>>p>>c,p!=0,c!=0){
 8          deque<int>dq;
 9      if(p<c){
10          for(int i=1;i<=p;i++){
11            dq.push_back(i);
12          }
13      }
14      else{
15          for(int i=1;i<=c;i++){
16            dq.push_back(i);
17          }
18      }
19      cases++;
20      printf("Case %d:\n",cases);
21      while(c--){
22          string com;
23          cin>>com;
24          if(com == "N"){
25              int e = dq.front();
26              cout<<e<<endl;
27              dq.pop_front();
28              dq.push_back(e);
29          }
30          else{
31              int num;
32              cin>>num;
33              for(deque<int>::iterator it = dq.begin();it!=dq.end();it++){
34                  if(*it == num){
35                  dq.erase(it);
36                  break;
37                  }
38 
39              }
40              dq.push_front(num);
41          }
42      }
43  }
44 
45 
46  return 0;}

Spoj Problem ACMCEG2C - Pick the candies (C++)

  The problem link may be found here.       Explanation: Use Deque to keep track of elements of the variety of candies. If i is gre...