Loading Similar Posts
Question 2 solution
#define ll long long
#define pb push_back
ll mod=1e9+7;
int sumDistance(vector<int>& nums, string s, int d) {
vector<ll> v;
ll n=nums.size();
ll d1=d;
vector<ll> v1;
for(int i=0;i<n;i++)
v1.pb(nums[i]);
for(int i=0;i<n;i++)
{
if(s[i]=='R')
{
v.pb(v1[i]+d1);
}
else
v.pb(v1[i]-d1);
}
sort(v.begin(),v.end());
ll sum = 0;
ll ans = 0;
for (ll i = 0; i < v.size(); i++) {
ans+=1ll*v[i]*i-sum;
ans%=mod;
sum+=v[i];
sum%=mod;
}
return ans;
}
Question 3 solution
#include <bits/stdc++.h>
using namespace std;
// Return (a+b)!/a!b!
int factorial(int a, int b)
{
int res = 1;
// finding (a+b)!
for (int i = 1; i <= (a + b); i++)
res = res * i;
// finding (a+b)!/a!
for (int i = 1; i <= a; i++)
res = res / i;
// finding (a+b)!/b!
for (int i = 1; i <= b; i++)
res = res / i;
return res;
}
// Return the Kth smallest way to reach given coordinate from origin
void Ksmallest(int x, int y, int k)
{
// if at origin
if (x == 0 && y == 0)
return;
// if on y-axis
else if (x == 0) {
// decrement y.
y--;
// Move vertical
cout << "S";
// recursive call to take next step.
Ksmallest(x, y, k);
}
// If on x-axis
else if (y == 0) {
// decrement x.
x--;
// Move horizontal.
cout << "E";
// recursive call to take next step.
Ksmallest(x, y, k);
}
else {
// If x + y C x is greater than K
if (factorial(x - 1, y) > k) {
// Move Horizontal
cout << "E";
// recursive call to take next step.
Ksmallest(x - 1, y, k);
}
else {
// Move vertical
cout << "S";
// recursive call to take next step.
Ksmallest(x, y - 1, k - factorial(x - 1, y));
}
}
}
// Driven Program
int main()
{
int x = 15, y = 15, k = 21477;
Ksmallest(x, y, k);
return 0;
}