Practice

# PROBLEM STATEMENT

Asgard is on lockdown and Thor is stuck at home with Loki and Loki being his mischievous self, hides the Mjolnir away from Thor and promises to return it if Thor can solve the queries given to him by Loki. Loki creates two arrays A and B.Each array consists of N positive integers of index starting from 1 to N. Thor has to fulfill the following types of queries over the arrays A and array B.
• 1 L R : Print the value of A[L] + B[L+1] + A[L+2] + B[L+3] + … up to the Rth term.
• 2 L R : Print the value of B[L] + A[L+1] + B[L+2] + A[L+3] + … up to the Rth term.
• For some reason, Thor’s magic seems to be not working today so he has to play by Loki’s rules. Please help Thor win back his hammer.

# SOLUTION

As we have to find the sum of alternate indexes of the two arrays, the problem would be simplified if we just swap all the even indexed elements of array A with the even indexed elements of array B. Now the question just reduces to the sum of the array for a given range depending on the query.

# SOLUTION CODE

``````#include<bits/stdc++.h>
using namespace std;
typedef long long int lint;
int main()
{
int n,q;
cin>>n>>q;
vector<lint>a(n+1);
vector<lint>b(n+1);
assert(n>=1 && n<=100000);
assert(q>=1 && q<=100000);
for(int i=1;i<=n;i++)
cin>>a[i];
for(int i=1;i<=n;i++)
cin>>b[i];
for(int i=2;i<=n;i+=2)
{
swap(a[i],b[i]);
}
for(int i=1;i<=n;i++)
{
a[i]+=a[i-1];
b[i]+=b[i-1];
}
for(int i=0;i<q;i++)
{
int x,l,r;
cin>>x>>l>>r;
assert(l<=r);
if(x==1)
{
if(l%2 !=0)
{
cout<<a[r]-a[l-1]<<endl;
}
else
{
cout<<b[r]-b[l-1]<<endl;
}
}
if(x==2)
{
if(l%2 == 0)
{
cout<<a[r]-a[l-1]<<endl;
}
else
{
cout<<b[r]-b[l-1]<<endl;
}
}
}
}``````