Header Ad

HackerEarth Sharpen the pencils problem solution

In this HackerEarth Sharpen, the pencils problem solution Madhav and Riya were getting bored. So they decided to play a game.
They placed N pencils in a line. Madhav starts to sharpen pencil from left to right, and Riya from right to left. For each pencil, its length is known.
Madhav sharpens with speed twice that of Riya. If a player starts to sharpen the pencil, other player can't touch it. If both players reach the same pencil simultaneously, Madhav gets to sharpen pencil as he snatches it away from Riya.

How many pencils each of the players will sharpen?


HackerEarth Sharpen the pencils problem solution


HackerEarth Sharpen the pencils problem solution.

#include<iostream>
using namespace std;

int main()
{
int t;
cin>>t;
while(t--)
{
int n;
cin>>n;
int arr[n+1];
for(int i=0;i<n;i++)
cin>>arr[i];

int i=0;
int j=n-1;
int count1=0,count2=0,sum1=0,sum2=0;
while(i<j)
{
if(sum1>sum2)
{
sum2+=(2*arr[j]);
count2++;
j--;
}
else if(sum2>sum1)
{
sum1+=arr[i];
i++;
count1++;
}
else
{
sum2+=(2*arr[j]);
count2++;
j--;
sum1+=arr[i];
i++;
count1++;
}
}
if(i==j && sum1<=sum2)
count1++;
if(i==j && sum1>sum2)
count2++;
cout<<count1<<" "<<count2<<endl;
}
}

Second solution

#include<bits/stdc++.h>
#define assn(n,a,b) assert(n<=b && n>=a)
using namespace std;
#define pb push_back
#define mp make_pair
#define clr(x) x.clear()
#define sz(x) ((int)(x).size())
#define F first
#define S second
#define REP(i,a,b) for(i=a;i<b;i++)
#define rep(i,b) for(i=0;i<b;i++)
#define rep1(i,b) for(i=1;i<=b;i++)
#define pdn(n) printf("%d\n",n)
#define sl(n) scanf("%lld",&n)
#define sd(n) scanf("%d",&n)
#define pn printf("\n")
typedef pair<int,int> PII;
typedef vector<PII> VPII;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef long long LL;
#define MOD 1000000007
LL mpow(LL a, LL n)
{LL ret=1;LL b=a;while(n) {if(n&1)
ret=(ret*b)%MOD;b=(b*b)%MOD;n>>=1;}
return (LL)ret;}
#define MAXN 100000
#define MAXV 10000000
int ar[MAXN+10];
LL pre[MAXN+10];
int main()
{
int t;
sd(t);
assn(t,1,1000);
while(t--){
int n;
sd(n);
assn(n,1,MAXN);
for(int i=1; i<=n; i++){
sd(ar[i]);
assn(ar[i],1,MAXV);
pre[i]=pre[i-1]+(LL)ar[i];
}
int i,ans;
for(i=1; i<=n; i++){
LL y=2*(pre[n]-pre[i]);
LL x=pre[i-1];
LL sol=y+2*ar[i]-x;
if(sol==0){ans=i-1;break;}
if(sol==3*ar[i]){ans=i;break;}
else if(sol>0 and sol<3*ar[i]){
if(x<=y)ans=i;
else ans=i-1;
break;
}
}
cout << ans << " " << n-ans << endl;
}
return 0;
}

Post a Comment

0 Comments