You are on page 1of 42

1.

Company Group

Jump to the solution

Booking Holdings is looking to acquire a new company for the group.


Joe is the one assigned to gather the information in the market. One of
the most popular questions for Joe is whether these two companies are
in the same company group or not. Your job is to help Joe answer this
question quickly.

Input

line 1: C, R, Q — number of companies, number of relationships,


number of questions

line 2 — (R+1): ai, bi — pair of parent company and subsidiary, means


that company ai is a parent company of company bi

line (R+2) — (R+2+Q): xj, yj — asking if xj and yi are in the same group
or not.

Constraint:

 0 < C < 100,000

 0 <= R <= C(C-1)/2


 0 < Q < 100,000

 1 <= ai, bi, xj, yj <= C

Output:

Q lines, each line shows either

YES when associated xj and yj are in the same group

NO, when associated xj and yj are not in the same group

Sample Input

535
12
13
34
12
23
14
24
25

Sample Output
YES
YES
YES
YES
NO

CODE — Company Group Solution


import
collections
def build_graph(C, relations):
parent_to_sub_graph = {i: [] for i in range(1, C +
1)}
for a, b in relations:
parent_to_sub_graph[a].append(b)
return parent_to_sub_graph
def find_group_parent(C, relations):
companies = set(range(1, C + 1))
for a, b in relations:
# a is parent of b
companies.discard(b)
return companies
def calculate_ans(C, relations):
graph = build_graph(C, relations)
group_parent = find_group_parent(C, relations)
company_to_group_number = dict()
for head in group_parent:
search_queue = collections.deque()
search_queue.append(head)
while search_queue:
cur_company = search_queue.popleft()
company_to_group_number[cur_company] = head
search_queue.extend(graph[cur_company])
return company_to_group_number
def get_input_line(func):
for x in input().split(" "):
yield func(x)
def main():
C, R, Q = get_input_line(int)
relations = []
for _ in range(R):
a, b = get_input_line(int)
relations.append((a, b))
# mapping of hotel no. to group no.
company_to_group_number = calculate_ans(C, relations)
for _ in range(Q):
x, y = get_input_line(int)
x_group = company_to_group_number[x]
y_group = company_to_group_number[y]
if x_group == y_group:
print("YES")
else:
print("NO")
if __name__ == '__main__':
main()

2. Happy Tourism

Jump to the solution

It’s World Tourism Day, and Agoda has launched a special promo code.
With each hotel booking a person makes, they can get a cashback
randomly and uniformly distributed from the range [1, maxCashBack]
in integer USD. A person will start with 0 cashback and can keep
applying this promo code until they secure a minimum of M USD in
total across all their future bookings.

To keep the customers happy, Agoda wants to ensure that most people
can make at least H USD from this promo code.
For this, Agoda has requested your help to calculate the probability of a
customer not being happy (total cashback received < H) with this
promo code given M, MaxCashBack, and H.

Please note that a user will keep applying this promo code for all his
bookings as long as allowed. Please return answers accurate up to 5
decimal places.

INPUT

The input will consist of 3 space-separated integers M, MaxCashBack


and H.

0 <= M <= H <= 10⁴

1 <= MaxCashBack <= 10⁴

OUTPUT

The calculated probability

Sample Input
1 10 11

Sample Output
1.00000
CODE — Happy Tourism Solution
def
happy_tourism(m,
max_cash_back,
h):
not_happy_limit = h - 1
if m == 0:
# not_happy_limit will be >=0
return 1.0
elif not_happy_limit < m:
# user will stop only after not_happy_limit
return 1.0
elif not_happy_limit >= (m - 1 + max_cash_back):
# max a user can reach is not_happy_limit
return 1.0
else:
# notHappyLimit lies between M to M - 1 + maxCashBack
prob_sum = 1.0
queue = [prob_sum]
ans = 0.0
for i in range(1, h):
prob_for_this = prob_sum * (1.0 / max_cash_back)
if i >= m:
ans += prob_for_this
if i < m:
prob_sum += prob_for_this
queue.append(prob_for_this)
if i >= max_cash_back:
prob_sum -= queue.pop(0)
return ans
if __name__ == "__main__":
inputs = input("")
sInputs = inputs.split(" ")
M, maxCashBack, H = int(sInputs[0]), int(sInputs[1]),
int(sInputs[2])
print(format(happy_tourism(M, maxCashBack, H), ".5f"))
3. Merge and Break

Jump to the solution


Watch how Satendra Tiwari, Development Manager, would solve this problem [from 3:16]

You are given N arrays of distinct positive integers. The ith array has
size K[i] (1 <= i <= N). You want to form a single array out of them,
sorted in ascending order. However, you can only perform 2 kinds of
operations:

Break
Choose any of the available arrays with size > 1, and then break it at
any point, so that array is divided into 2 non-empty parts.

For example, an array of size x & the 2 divided parts have sizes x1 and
x2 respectively x1 + x2 = x , x1 > 0 , x2 > 0. Then the cost of this
operation is min(x1, x2).

Merge
Choose any 2 arrays and merge them, interleaving their elements
without rearranging the elements of individual arrays. In other words,
if the 2 arrays merged had sizes x1&x2, the merged array will have size
x1 + x2, and both the individual arrays will be present as
disjoint subsequences in the merged array.

For example, 2 arrays merged had sizes x1 & x2 (x1 > 0 , x2 > 0). Then
the cost of this operation is x1 + x2.
You have to find out what is the min cost to create a single sorted
array out of them.

INPUT

The first line contains an integer T — the number of test cases. Then T
test cases follow. The first line of a test case contains a single integer N,
the number of arrays you have. Then N lines follow. The first integer in
the ith of the next N lines is K[i], the size of the ith array, and is
followed by K[i] space-separated integers representing elements of ith
array. All the numbers in each of the arrays are integers in the range
[1,1e9]. Within a single test case, all the numbers in the array are
distinct. The sum of K[i] in any input file will not exceed 4 * 1e5.

Constraints

1 <= T <= 7
1 <= N <= 100000
1 <= K[i] <= 100000
1 <= I <= N

Sample Input

3
2
213
12
1
3321
1
3 1000000000 7000 900000

OUTPUT

For each test case, print on a new line, a single integer denoting the
minimum cost required to create a single sorted array using the
operations mentioned in the problem statement.

Sample Output

3
7
4

CODE — Merge and Break Solution


from
heapq
import
heappush,
heappop,
heapify
def find_splits_and_cost(arrays):
ans = 0
splits_arr = []
for a in arrays:
split_loc = [i for i in range(1, len(a)) if a[i - 1] > a[i]]
splits = [j - i for i, j in zip([0, *split_loc], [*split_loc,
len(a)])]
ans += len(a) - max(splits)
splits_arr += splits
return splits_arr, ans
def get_merge_cost(splits):
cost = 0
heapify(splits)
while len(splits) > 1:
val = heappop(splits) + heappop(splits)
cost += val
heappush(splits, val)
return cost
def get_total_cost(arrays):
splits, split_cost = find_splits_and_cost(arrays)
merge_cost = get_merge_cost(splits)
total_cost = split_cost + merge_cost
return total_cost
def main():
T = int(input())
for cas in range(T):
N = int(input())
arrays = [[*map(int, input().split())][1:] for i in range(N)]
cost = get_total_cost(arrays)
print(cost)
if __name__ == '__main__':
main()

4. Shuffled String

Jump to the solution

Mr Agoji is given a shuffled string made by randomly shuffling a


special string.

A string is special only if it is formed by joining some special words any


number of times. Special words are mapping of numbers (0 <=
number < 10) to their words, for example, mapping of ‘0’ to ‘zero,’
mapping of ‘1’ to ‘one,’ and so on.

Mr Agoji is asked to convert the shuffled string to the smallest special


number. A special number is a number formed using numbers (0 <=
number < 10) without any leading zeroes.

Mr Agoji, who is not so good with numbers and strings, has asked for
your help.

INPUT

The first line of the input will contain T, number of test cases. For each
test case, there will be a, s shuffled string, on a separate line.

1 <= T <= 100

1 <= s.length <= 100000

OUTPUT

For each test case, on a new line, the smallest special number is in the
string format.

Some notes on output:


Shuffled string will always be able to convert into at least one valid
special string.

Shuffled string will only contain small English alphabets.

If shuffled string contains only zeroes, you should output “0”.

Sample Input

2
“ewtooetzrowon”
“ttnrwoooeeefurh”

Sample output

1022
1234

CODE — Shuffled String Solution


import
collection
s
def count_character(shuffled_string):
char_count = dict()
for char in shuffled_string:
char_count[char] = char_count.get(char, 0) + 1
return char_count
def do_count_for_unique_char_digits(char_count, digit_count):
digit_count[0] = char_count.get('z', 0) # [z]ero
digit_count[2] = char_count.get('w', 0) # t[w]o
digit_count[4] = char_count.get('u', 0) # fo[u]r
digit_count[6] = char_count.get('x', 0) # si[x]
digit_count[8] = char_count.get('g', 0) # ei[g]ht
def do_count_for_other_digits(char_count, digit_count):
# [o]ne, zer[o], tw[o], f[o]ur
digit_count[1] = char_count.get('o', 0) - digit_count[0] - digit_count[2] -
digit_count[4]
# t[h]ree, eig[h]t
digit_count[3] = char_count.get('h', 0) - digit_count[8]
# [f]ive, [f]our
digit_count[5] = char_count.get('f', 0) - digit_count[4]
# [s]even, [s]ix
digit_count[7] = char_count.get('s', 0) - digit_count[6]
# n[i]ne, f[i]ve, s[i]x, e[i]ght
digit_count[9] = char_count.get('i', 0) - digit_count[5] - digit_count[6] -
digit_count[8]
def count_digit(char_count):
digit_count = [0] * 10
do_count_for_unique_char_digits(char_count, digit_count)
do_count_for_other_digits(char_count, digit_count)
return digit_count
def find_smallest_non_zero(digit_count):
for number, count in enumerate(digit_count):
if number != 0 and count > 0:
return number
def construct_smallest_number(digit_count):
digit_list = []
# first number
smallest_non_zero = find_smallest_non_zero(digit_count)
digit_list.append(str(smallest_non_zero))
digit_count[smallest_non_zero] -= 1
# other numbers
for number, count in enumerate(digit_count):
digit_list.extend([str(number)] * count)
return "".join(digit_list)
def get_smallest_special_number(shuffled_string):
char_count = count_character(shuffled_string)
digit_count = count_digit(char_count)
total_non_zero_digits_count = sum(digit_count[1:])
if total_non_zero_digits_count <= 0:
return "0"
smallest_special_number = construct_smallest_number(digit_count)
return smallest_special_number
def main():
T = int(input())
for _ in range(T):
shuffled_string = input()
smallest_special_number = get_smallest_special_number(shuffled_string)
print(smallest_special_number)
if __name__ == '__main__':
main()

5. Stone Game

Jump to the solution

Mr Agoji was bored in lockdown, so he designed a game for himself.


The game is played on a sequence of piles of stones. Let's say there are
N integers s1, s2, …., sn, describing the number of stones in each pile.
On each turn, Mr Agoji picks a pair of non-empty adjacent piles i and
i+1 and takes 1 stone from each. If a pile(ith) becomes empty, then its
adjacent piles(i-1th and i+1th) do not become adjacent.

The game ends when Mr Agoji can’t make a turn anymore. He wins if
he can clear all the piles. We consider a sequence of piles winning if Mr
Agoji can start with it and win the game. You are given a sequence of
integers s1, s2, s3, …., sn. You have to find out how many subsegments
of this sequence are winning. A subsegment is defined as a continuous
sequence from L to R, i. e. sL, sL+1, ….., sR, given 1 <= L < R <= N.

INPUT
The first line of the input contains number of test cases, T. The next T
test cases follow an integer N, denoting the number of piles of stones.
Next line contains N integers, s1, s2, s3,……, sn describing the number
of stones in each pile.

1 <= T <= 10⁵

1 <= N <= 10⁵

0 <= si <= 10⁹

OUTPUT

Print a single integer for each test case — the answer to the problem.

Sample Input

6
2
22
3
123
4
1111
4
1221
4
1212
8
12121212

Sample output

1
0
4
2
1
3

CODE — Stone Game Solution


#include
<iostream>
#include <map>
using namespace std;
void increment_counting_map(map<long long, long long> &counting_map, long long
key)
{
auto it=counting_map.find(key);
if(it != counting_map.end())
{
pair<long long, long long> kv_pair = *it;
counting_map.erase(it);
kv_pair.second++;
counting_map.insert(kv_pair);
}
else
{
counting_map[key]=1;
}
}
long long find_in_map(map<long long, long long> &counting_map, long long key)
{
auto it=counting_map.find(key);
if(it != counting_map.end())
{
return it->second;
}
return 0;
}
void remove_if_greater(map<long long, long long> &counting_map, long long val)
{
while(!counting_map.empty())
{
auto it = counting_map.end();
it--;
if(it->first > val)
counting_map.erase(it);
else
break;
}
}
void remove_if_lesser(map<long long, long long> &counting_map, long long val)
{
while(!counting_map.empty())
{
auto it=counting_map.begin();
if(it->first < val)
counting_map.erase(it);
else
break;
}
}
long long calcualte_ans(long long N, long long piles[])
{
map<long long, long long> counting_map;
long long cf=0, ans=0;
for (long long i=0; i<N; i++)
{
long long stone_count = piles[i];
if(stone_count == 0)
ans++;
if(i%2 == 1) // odd index
{
cf+=stone_count;
ans+=find_in_map(counting_map, cf);
increment_counting_map(counting_map, cf-stone_count);
remove_if_greater(counting_map, cf);
}
else
{ // even index
cf-=stone_count;
ans+=find_in_map(counting_map, cf);
increment_counting_map(counting_map, cf+stone_count);
remove_if_lesser(counting_map, cf);
}
}
return ans;
}
int main()
{
int T;
cin >> T;
for(int t=0; t<T; t++){
int N;
cin >> N;
long long piles[N];
for(long long i=0; i<N; i++){
long long stone_count;
cin >> stone_count;
piles[i] = stone_count;
}
long long ans = calcualte_ans(N, piles);
cout << ans << endl;
}
return 0;
}

6. Best Hotel
Jump to the solution

Mr Agoji plans to travel to a new city for his vacation. There are N
number of hotels available in that city. Each hotel has information on
the price/night and rating. Mr Agoji has a tight budget for his trip, so
he can’t afford to book a costly hotel but wants the best experience in
his budget range, so he plans different budgets for his trip.

There are Q different budget options for hotel booking in his budget
plans. Mr Agoji, who is not that good at calculations, has asked for your
help to decide on the best-rated hotel in his budget.

You are given a list of hotel names, the price per night, and the hotel’s
rating. For different budget ranges, you have to find the best-rated
hotel for Mr Agoji.

Note that if two hotels in that range have the same rating, you should
output the one with the lowest booking price per night, and no two
hotels should have the same price per night.

INPUT

The first line contains an integer T — the number of test cases. The first
line of a test case contains a single integer N, the number of hotels you
have and an integer Q, the number of budget ranges. Then N lines
follow. A string s, the hotel name, integer p, price of the hotel per night
and a double r, rating of the hotel. These will be space separated.
Note that the hotel name does not contain any spaces. Next, Q lines
follow two space-separated integers L, lower limit of budget range and
U, upper limit of budget range. Note that the budget range is
specifically for hotel booking and not for the whole trip.

Constraint

1 <= T <= 7
1 <= N <= 100000
1 <= Q <= 100000
1 <= s.length <= 1000
1 <= p <=100000
0.1 <= r <= 10.0
1 <= U <= 100000
0 <= L <= U

OUTPUT

For each test case, for each query, print on a new line, a string denoting
the best-rated hotel in the budget range of the query.

Sample Input

1
33
a 1000 8.1
b 800 7.6
c 1200 7.9
600 1400
700 900
300 12000

Sample output

a
b
a

CODE — Best hotel Solution


import
math
class Hotel:
def __init__(self, name='default_hotel', price=100001, rating=0.0):
self.name = name
self.price = price
self.rating = rating
default_hotel = Hotel()
def build_tree(hotels_map, seg_tree, low, high, pos):
if low == high:
seg_tree[pos] = hotels_map.get(low, default_hotel)
return
mid = math.floor((low + high) / 2)
build_tree(hotels_map, seg_tree, low, mid, 2 * pos + 1)
build_tree(hotels_map, seg_tree, mid + 1, high, 2 * pos + 2)
hotel_left: Hotel = seg_tree[2 * pos + 1]
hotel_right: Hotel = seg_tree[2 * pos + 2]
if hotel_left.rating > hotel_right.rating:
seg_tree[pos] = hotel_left
elif hotel_left.rating < hotel_right.rating:
seg_tree[pos] = hotel_right
else:
if hotel_left.price < hotel_right.price:
seg_tree[pos] = hotel_left
else:
seg_tree[pos] = hotel_right
def query(idx, low, high, budget_low, budget_high, seg_tree):
# no overlap: l > high || r < low
if budget_low > high or budget_high < low:
return default_hotel
# complete overlap
if low >= budget_low and high <= budget_high:
return seg_tree[idx]
# partial overlap
mid = math.floor((low + high) / 2)
hotel_left: Hotel = query(2 * idx + 1, low, mid, budget_low, budget_high, seg_tree)
hotel_right: Hotel = query(2 * idx + 2, mid + 1, high, budget_low, budget_high,
seg_tree)
if hotel_left.rating > hotel_right.rating:
return hotel_left
elif hotel_left.rating < hotel_right.rating:
return hotel_right
else:
if hotel_left.price < hotel_right.price:
return hotel_left
else:
return hotel_right
def solve(price_lower_bound, price_upper_bound, hotels_map, Q):
seg_tree = [Hotel() for i in range(4 * price_upper_bound)]
build_tree(hotels_map, seg_tree, price_lower_bound, price_upper_bound, 0)
for i in range(Q):
budget_low, budget_high = (int(x) for x in input().split(" "))
assert budget_low >= 1
assert budget_high <= 100000
res = query(0, price_lower_bound, price_upper_bound, budget_low, budget_high,
seg_tree)
print(res.name)
def main():
price_lower_bound = 1 # as there was discrepancy in problem description and TC. 0
here is also correct sol
price_upper_bound = 100000
T = int(input())
for _ in range(T):
N, Q = (int(x) for x in input().split(" "))
hotels_map = {}
for _ in range(N):
tokens = input().split(" ")
name, price, rating = tokens[0], int(tokens[1]), float(tokens[2])
hotels_map[price] = Hotel(name, price, rating)
solve(price_lower_bound, price_upper_bound, hotels_map, Q)
if __name__ == '__main__':
main()

1. Agojis Equal Day Trip

Jump to the solution


Agoji is a traveler who loves to explore new cities. He has planned a
trip to visit different cities around the world. Agoji has received N
offers for different cities for his trip. Each offer contains the city name,
the maximum number of days in the city, and the price per day. With
each offer, he can choose to stay for any number of days between 0 and
max number of days.

His goal is to maximize the total stay while minimizing the total cost.
The number of days he stays per city must be equal as he does not want
to visit some cities more than others. It’s not required for him to visit
all cities available.

Can you help him find the best deals for his trip?

Input Format

The first line of the input is an integer, N, which represents the number
of offers.

Following that, there are N lines, each consisting of three values


separated by spaces. The first value is a string, city_name, representing
the name of a city. The second value is an integer, max_num_days,
indicating the maximum number of days a traveler can stay in that city.
The third value is an integer, cost_per_day, representing the daily cost
of staying in the city.

Constraints
Output Format

Print two values — maximum number of days and minimum cost

Sample Input

5
Nyc 4 100
Bangkok 3 10
Nyc 2 15
Warsaw 1 12
Paris 3 80

Sample Output

9 400

Explanation

An optimal solution is to choose offers 1, 2, 3, and 5, allowing Mr. Agoji


to spend three days each in New York City, Bangkok, and Paris for a
total of nine days. This approach satisfies all the problem constraints
and minimizes the cost of the entire trip, which comes out to be 400.
Sample Input

8
London 2 100
Delhi 1 50
Paris 3 200
Rome 2 100
London 1 40
Paris 1 80
Bangkok 5 170
Delhi 3 75

Sample Output

12 1430

Agojis Equal Day Trip — Solution


Note:
Another
approach
is to
first
determine
the
maximum
number of
days, and
then
identify
the
minimum cost among all the indices that have the maximum number of days.
"""
from collections import defaultdict
import heapq
def main():
N = int(input())
cities = defaultdict(list)
for _ in range(N):
city, days, cost = input().split()
days, cost = int(days), int(cost)
cities[city].append((days, cost))
cities = list(cities.values())
pq = []
curr_cost, total_cost, num_days, max_days, min_cost = 0, 0, 0, 0, float(
'inf')
for i, trips in enumerate(cities):
trips.sort(key=lambda x: x[1])
curr_cost += trips[0][1]
pq += [(trips[0][0], i, 1)]
heapq.heapify(pq)
while pq:
days, city, trip = pq[0]
total_cost += (days-num_days)*curr_cost
cost1, cost2 = cities[city][trip -
1][1], cities[city][trip][1] if trip <
len(cities[city]) else 0
curr_cost += cost2 - cost1
num_days = days
if trip == len(cities[city]):
nmax_days = num_days * len(pq)
if nmax_days >= max_days:
if nmax_days == max_days:
min_cost = min(min_cost, total_cost)
else:
min_cost = total_cost
max_days = nmax_days
heapq.heappop(pq)
total_cost -= sum([d*c for d, c in cities[city]])
else:
days += cities[city][trip][0]
heapq.heapreplace(pq, (days, city, trip+1))
return max_days, min_cost

if __name__ == '__main__':
max_days, min_cost = main()
print(f"{max_days} {min_cost}")
2. Search Result Ranking

Jump to the solution

Agoda has millions of hotels listed on its website. Each hotel has an id,
a name, a location, and information about the type of accommodation
it offers. To advertise these hotels on Elgo, Agoda has built a list of
keywords that are relevant to each hotel. For example, the keywords
for the hotel “The Grand Hotel” might be “luxury,” “spa,” “beach,”
“grand,” “hotel,” “resort” etc.

Each keyword is associated with a score. The score is a positive integer


indicating the keyword’s relevance to the hotel. For example, the
keyword “grand” might have a score of 100, while the keyword “hotel”
might have a score of 10. The score of a keyword is independent of the
other keywords. It should be noted that the keywords are not unique,
and a keyword can have different scores for different hotels.

Elgo is a search engine that allows users to search for hotels by search
queries. A search query is a string of words. The search results are
ranked by the relevance of the hotels to the search query. The relevance
of a hotel to a search query is the sum of the scores of the keywords
relevant to the hotel, i.e., the keywords present in the search query.

For example, suppose we have a hotel with id 1 and the keywords


“grand” and “hotel” with scores 100 and 10, respectively. In that case,
the relevance of the hotel to the search query “grand hotel”, “luxury
hotel bangkok” and “spa in bangkok” is 110, 10, and 0 (irrelevant),
respectively.

Elgo has a limit on the number of hotels that can be displayed in the
search results. If the number of hotels relevant to the keywords exceeds
the limit, Elgo will only display the hotels with the highest relevance
sorted in descending order of relevance. If there are multiple hotels
with the same relevance, the hotels with the lowest id will be displayed
first.

Given lists of hotels, their keywords, and search queries, print a list of
recommended hotels for each query.

Input Format

The first line contains two space-separated integers, N and M,


where N is the number of hotels and M is the number of search
queries.

The next N lines start with two space-separated integers, H and K,


where H is the id of the hotel, and K is the number of keywords
associated with the hotel. It is followed by K space-separated keyword-
score pairs, where each keyword-score pair consists of a keyword and a
score separated by a space. The keyword is a string of lowercase
English letters. The score is a positive integer
The next M lines start with an integer L, representing the number of
words in search query, followed by L space-separated words. Each
word is a string of lowercase English letters.

Constraints

All hotel ids are unique

Keywords for each hotel are unique

Output Format

For each search query, print the hotel ids displayed in the search
results. The ids must be printed in the order they appear in the search
results. If there are no hotels that are relevant to the search query,
print -1. If there are more than 10 hotels that are relevant to the search
query, print only the first 10 hotels.

Sample Input
3 2
101 3 grand 100 hotel 10 center 5
201 3 luxury 100 bangkok 10 hotel 1
301 2 goa 50 resort 50
2 grand hotel
1 goa

Sample Output

101 201
301

Explanation

For search query “grand hotel”, the relevance of hotel with id 101, 201,
and 301 are 110, 10, and 0, respectively. Since the first two hotels are
relevant to the search query, they are displayed in the search results.
The relevance of hotel with id 301 is 0, so it is not displayed in the
search results.

For search query “goa”, the relevance of hotel with id 101, 201, and 301
are 0, 0, and 50, respectively. Since only the third hotel is relevant to
the search query, it is displayed in the search results.

Sample Input

5 5
10 3 delhi 100 holiday 5 hotel 50
11 3 delhi 100 business 6 hotel 30
12 3 spa 100 luxury 20 hotel 5
14 3 delhi 100 luxury 9 hotel 10
15 3 london 500 luxury 8 hotel 30
3 luxury business hotel
3 cheap hotel london
3 delhi luxury hotel
4 vry qiravx heqpc deu
2 business holiday

Sample Output

10 15 11 12 14
15 10 11 14 12
10 11 14 15 12
-1
11 10

Search Result Ranking — Solution


Approach:
Dynamic
Programming,
Combinatorics
, Heap,
Implementatio
n
R = result size = 10
Time Complexity: O(N * 2^K + M * 2^L * R)
Space Complexity: O(N * 2^K)
"""
import heapq
class HotelScore(object):
def __init__(self, hid, score):
self.hid = hid
self.score = score
self.__key = (score, -hid)
def __lt__(self, other):
return self.__key < other.__key
def keyword_comb(keywords):
keywords = list(sorted(keywords))
comb = [((), 0)]
for keyword, score in keywords:
comb += [(c + (keyword,), s + score) for c, s in comb]
return comb[1:]
def search_comb(search_queries):
search_queries = list(sorted(search_queries))
comb = [()]
for query in search_queries:
comb += [c + (query,) for c in comb]
return comb[1:]
def main():
N, M = map(int, input().split())
dp = {}
for _ in range(N):
line = input().split()
hid = int(line[0])
keywords = line[2::2]
scores = list(map(int, line[3::2]))
for comb, score in keyword_comb(zip(keywords, scores)):
if comb not in dp:
dp[comb] = []
hotels = dp[comb]
heapq.heappush(hotels, HotelScore(hid, score))
if len(hotels) > 10:
heapq.heappop(hotels)
for _ in range(M):
line = input().split()
query = line[1:]
hotels = {}
for comb in search_comb(query):
for hotel in dp.get(comb, []):
hotels[hotel.hid] = max(hotels.get(hotel.hid, 0),
hotel.score)
hotels = [(-score, hid) for hid, score in hotels.items()]
hotels.sort()
hotels = [hid for _, hid in hotels[:10]]
if len(hotels) == 0:
print(-1)
else:
print(' '.join(map(str, hotels)))
if __name__ == "__main__":
main()
3. Trip Planner

Jump to solution

Agoda’s objective is to provide the best price to customers, but it is not


always easy. There are many factors that affect the price. For example,
the price of a hotel room depends on the number of rooms available,
the number of people who want to book the room, etc.

For each hotel room, Agoda has a price for each day of the year. Agoda
offers discounts for long stays. It also offers “Agoda Cash” on specific
days in the year to make customers happy and encourage them to book
more.

Mr. Agoji, who always books hotels through Agoda is planning his next
long holiday. Specifically, he wants to go to Agodaland, which
has N hotels for D days. He knows the price of each hotel for each day.
He also got a secret deal message from Agoda for a set of P hotels that
if he books a hotel room Q for at least X consecutive days, he gets Y %
discount on the total price of the consecutive stay at the hotel. The total
discount is rounded up to the smallest integer not smaller than the
discount itself. To make things more interesting, when he logged in to
Agoda app on his phone, he got a notification of all available Agoda
Cash for a list of hotel rooms and days.
He cannot wait to book the hotel rooms. He knows that he can
maximize Agoda Cash and minimize the cost of staying in Agodaland
by optimally selecting which hotel room to book for each day.
However, there is another challenge for him. He must travel from one
hotel to other, but not all hotels are connected to each other

Specifically, there are M bidirectional roads each connecting two


hotels, U and V, with a cost C of traveling from one hotel to other. Mr.
Agoji can travel from one hotel to another only if there is a sequence of
roads connecting them. For this problem you can assume that traveling
from one hotel to another is instantaneous.

Mr. Agoji has a superpower, on day one he can magically go to any one
hotel. After that he can only travel from one hotel to another using the
roads.

Mr. Agoji wants to know the maximum Agoda Cash he can get and the
minimum cost of staying in Agodaland. Can you help him? It should be
noted that you should maximize Agoda Cash first and then minimize
the cost of staying in Agodaland.

Warning: Please note that if you’re using a slower programming


language like Python, there’s a possibility that the code might exceed
the time limit and result in a timeout error on large input.

Input Format
The first line contains three space-separated integers number of
hotels N, number of days D, and number of roads M.

The next N lines contain D space-separated integers each. The Jᵗʰ


integer in the ith line Priceᵢⱼ denotes the price of ith hotel on day J.

The next M lines contain three space-separated integers hotel U,


hotel V and cost of traveling C.

The next line contains an integer P. The next P lines contain three


space-separated integers hotel Q, number of consecutive days X, and
discount Y(in percentage).

The next line contains an integer, the number of Agoda Cash K. The
next K lines contains three space-separated integers hotel contain R,
day S and Agoda Cash T.

Constraints

There are three types of testcases. Constraints on the number of


hotels, N, and the number of days, D, are different for each type but
constraints on other parameters are the same

Small Input

1 ≤ N , D ≤ 8
Medium Input

9 ≤ N , D ≤ 20

Large Input

21 ≤ N , D ≤ 250

Constraints on other parameters

0 ≤ M ≤ 1000

0 ≤ P ≤ N

0 ≤ K ≤ N × D

1 ≤ U, V, Q, R ≤ N

1 ≤ X, S ≤ D

1 ≤ Y ≤ 100

1 ≤ Priceᵢⱼ, T ≤50000

U ≠ V

All Q are distinct
All pair of (R, S) are distinct

Output Format

Two space separated integers, the maximum Agoda Cash, and the
minimum cost of staying in Agodaland.

Sample Input

3 3 3
10 25 5
20 30 1
2 2 2
1 2 10
2 3 5
1 3 6
1
2 2 50
3
1 1 7
1 2 10
2 2 10

Sample Output

17 35

Explanation

There are several ways to maximize the amount of Agoda cash earned,
but one optimal solution is to stay at hotel 1 for all three days, which
would earn $17 in Agoda cash. However, the cost of this stay would be
$40. After trying all possible combinations, it becomes clear that it’s
impossible to earn more than $17 in Agoda cash.

However, it is possible to minimize the overall cost of the trip while


still earning the maximum amount of Agoda cash. For example, the
traveler could stay at hotel 1 on the first day, then travel to hotel 2 on
the second day and stay there for the next two days. This would cost
$10 for staying at hotel 1 on day 1, $10 for traveling from hotel 1 to
hotel 2 on day 2, $31 for staying at hotel 2 on days 2 and 3, and a
discount of $16 (50% of $31 rounded up for staying at hotel 2 for at
least two consecutive days) for a total of $35.

Sample Input

2 5 1
25 25 50 50 50
100 120 60 60 60
1 2 20
1
2 2 20
6
1 2 30
1 3 40
2 1 20
2 2 30
2 3 40
2 4 10

Sample Output

100 309
Trip Planner — Solution
""
"

Approach: DP

Time Complexity: O(N^3 + ND * (N + D))

Space Complexity: O(N^2 + ND)

"""

from itertools import accumulate

def floyd_warshall(arr, N):

for k in range(N):

for i in range(N):

for j in range(N):

arr[i][j] = min(arr[i][j], arr[i][k] + arr[k][j])

def main():

N, D, M = map(int, input().split())

prices = [list(map(int, input().split())) for _ in range(N)]

prices = [[0] + list(accumulate(p)) for p in prices]

travel_cost = [[float('inf')] * N for _ in range(N)]

for i in range(N):

travel_cost[i][i] = 0

for _ in range(M):

u, v, w = map(int, input().split())

u, v = u - 1, v - 1

w = min(w, travel_cost[u][v])

travel_cost[u][v], travel_cost[v][u] = w, w

discounts = [0] * N
P = int(input())

for _ in range(P):

q, x, y = map(int, input().split())

discounts[q-1] = (x, y)

def calc_price(hotel, start_day, end_day):

price = prices[hotel][end_day]-prices[hotel][start_day]

if discounts[hotel] and discounts[hotel][0] <= end_day - start_day:

price -= (price*discounts[hotel][1]+99)//100

return price

K = int(input())

agoda_cash = [[0] * D for _ in range(N)]

for _ in range(K):

R, S, T = map(int, input().split())

agoda_cash[R-1][S-1] = T

dp1 = [[(float('-inf'), float('-inf'))] * (D+1) for _ in range(N)]

dp2 = [[(float('-inf'), float('-inf'))] * (D+1) for _ in range(N)]

for i in range(N):

dp2[i][0] = (0, 0)

floyd_warshall(travel_cost, N)

def combine(plan1, plan2):

return (plan1[0]+plan2[0], plan1[1]+plan2[1])

for day in range(0, D):

for i in range(N):

ag_cash = 0

for j in range(day, D):


ag_cash += agoda_cash[i][j]

dp1[i][j] = max(dp1[i][j], combine(dp2[i][day], (ag_cash, -calc_price(i,


day, j+1))))

for i in range(N):

for j in range(N):

if i != j and travel_cost[i][j] != float('inf'):

dp2[j][day+1] = max(dp2[j][day+1], combine(dp1[i][day], (0, -


travel_cost[i][j])))

best = max(dp1[i][D-1] for i in range(N))

return (best[0], -best[1])

if __name__ == "__main__":

print(*main())

You might also like