COPS : Cops and the Thief Devu
Link for the problem: COPS
Solution:
We will find the extremum for every cop i.e. leftmost and the rightmost house in which a cop can search for thief Devu.
We can use a colouring method to solve this problem. Let an array of size 101 so that it has index 1 and 100 in it.
Initialize it with zeros i.e. it is uncoloured. We have to colour the array for every cop. To do this in O(n) complexity, colour the leftmost element by -1 and element after rightmost element by 1.
So that when we do the cumulative sum in the array, the elements in the range of cop will be negative and other will be zero.
So summing for every cop, if the given element is negative then the cop can reach that house and if it is 0 or positive, then no cop can reach that house.
Code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int m,x,y;
scanf("%d %d %d",&m,&x,&y);
int a[m],i,j,k,d=x*y;
for(i=0;i<m;i++)
scanf("%d",&a[i]);
int b[102]={0};
for(i=0;i<m;i++)
{
int m1,m2;
m1=max(a[i]-d,1);
m2=min(a[i]+d+1,101);
b[m1]+=-1;
b[m2]+=1;
}
int c=0;
for(i=1;i<=100;i++)
{
b[i]=b[i-1]+b[i];
if(b[i]>=0)
c++;
}
printf("%d\n",c);
}
return 0;
}
Link for the problem: COPS
Solution:
We will find the extremum for every cop i.e. leftmost and the rightmost house in which a cop can search for thief Devu.
We can use a colouring method to solve this problem. Let an array of size 101 so that it has index 1 and 100 in it.
Initialize it with zeros i.e. it is uncoloured. We have to colour the array for every cop. To do this in O(n) complexity, colour the leftmost element by -1 and element after rightmost element by 1.
So that when we do the cumulative sum in the array, the elements in the range of cop will be negative and other will be zero.
So summing for every cop, if the given element is negative then the cop can reach that house and if it is 0 or positive, then no cop can reach that house.
Code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int m,x,y;
scanf("%d %d %d",&m,&x,&y);
int a[m],i,j,k,d=x*y;
for(i=0;i<m;i++)
scanf("%d",&a[i]);
int b[102]={0};
for(i=0;i<m;i++)
{
int m1,m2;
m1=max(a[i]-d,1);
m2=min(a[i]+d+1,101);
b[m1]+=-1;
b[m2]+=1;
}
int c=0;
for(i=1;i<=100;i++)
{
b[i]=b[i-1]+b[i];
if(b[i]>=0)
c++;
}
printf("%d\n",c);
}
return 0;
}
No comments:
Post a Comment