In this HackerEarth Holi And Colorful houses problem solution Monk is given the task of distributing sweets Q number of times. Every time he is asked to travel from the xth house to the yth house to distribute the sweets.
The distribution strategy is that he starts from the xth house and he has to give 1 sweet to a house only when he travels from greenhouse to a red house or vice-versa. Monks can travel from xth house to yth house either in a clockwise direction or in the anti-clockwise direction.
Monk wants your help to find the minimum number of sweets he should carry to complete his journey.


HackerEarth Holi And Colorful houses problem solution


HackerEarth Holi And Colorful houses problem solution.

#include<bits/stdc++.h>
using namespace std;
#define ll int
int main()
{
    freopen("samp.txt","r",stdin);
    freopen("sout.txt","w",stdout);
    ll t,n,q,x,y,i,j,cur,ans,val,val1;
    string s;
    cin>>t;
    assert(t>=1&&t<=100);
    while(t--)
    {
        cin>>n>>q;
        assert(n>=1&&n<=1000);
        assert(q>=1&&q<=1000);
        cin>>s;
        s=s+s;
        s=" "+s;
        while(q--)
        {
            val=val1=0;
            cin>>x>>y;
            if(x>y)
            swap(x,y);
            cur=s[x];
            for(i=x;i<=y;i++)
            {
                if(s[i]!=cur)
                {
                    cur=s[i];
                    val++;
                }
            }
            x+=n;
            cur=s[y];
            for(i=y;i<=x;i++)
            {
                if(s[i]!=cur)
                {
                    cur=s[i];
                    val1++;
                }
            }
            ans=min(val,val1);
            cout<<ans<<"\n";
        }
    }
    return 0;
}


Second solution

#include<bits/stdc++.h>
using namespace std;
int main()
{
  int t;
  cin>>t;
  assert(t>=1 && t<=1e2);
  while(t--)
  {
    int n,q;
    cin>>n>>q;
    assert(n>=1 && n<=1e3);
    assert(q>=1 && q<=1e3);
    string s;
    cin>>s;
    for(int i=0;i<s.size();i++)assert(s[i]=='G' || s[i]=='R');
    assert(s.size()==n);
    while(q--)
    {
      int x,y,a1=0,a2=0,ans;
      cin>>x>>y;x--;y--;
      if(x>y){swap(x,y);}
      for(int i=x+1;i<=y;i++)
        a1+=(s[i]!=s[i-1]);
      for(int i=y+1;i<=n-1;i++)
        a2+=(s[i]!=s[i-1]);
      a2+=(s[0]!=s[n-1]);
      for(int i=1;i<=x;i++)
        a2+=(s[i]!=s[i-1]);
      //cout<<a1<<" "<<a2<<"\n";
      cout<<min(a1,a2)<<"\n";
    }
  }
  return 0;
}