Accessory Collection


Problem Statement :


Victoria is splurging on expensive accessories at her favorite stores. Each store stocks  types of accessories, where the  accessory costs  dollars (). Assume that an item's type identifier is the same as its cost, and the store has an unlimited supply of each accessory.

Victoria wants to purchase a total of  accessories according to the following rule:

For example, if , , and , then she must choose  accessories such that any subset of  of the  accessories will contain at least  distinct types of items.

Given , , , and  values for  shopping trips, find and print the maximum amount of money that Victoria can spend during each trip; if it's not possible for Victoria to make a purchase during a certain trip, print SAD instead. You must print your answer for each trip on a new line.


Input Format

The first line contains an integer, , denoting the number of shopping trips.
Each of the  subsequent lines describes a single shopping trip as four space-separated integers corresponding to L, A , N , and D, respectively.


Output Format

For each shopping trip, print a single line containing either the maximum amount of money Victoria can spend; if there is no collection of items satisfying her shopping rule for the trip's L, A , N , and D  values, print SAD instead.



Solution :



title-img


                            Solution in C :

In   C  :






#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>

int main(){
    int T; 
    scanf("%d",&T);
    for(int a0 = 0; a0 < T; a0++){
        int L; 
        int A; 
        int N; 
        int D; 
        scanf("%d %d %d %d",&L,&A,&N,&D);
        if (D == 1) {
            printf("%lld\n", (long long)A*L);
            continue;
        }
        int max, min, i, q, r;
        long long count, result = 0;
        max = (N-1)/(D-1);
        if ((L-(N-1)+max-1)/max+D-1 > A) {
            printf("SAD\n");
            continue;
        }
        min = (L-(N-1)+A-(D-1)-1)/(A-(D-1));
        for (i=max; i>=min; i--) {
            q = (L-(N-1))/i;
            r = (L-(N-1))%i;
            count = (long long)(A-(D-1+q))*r + (long long)(A-(D-1+q)+1+A-1)*(D-2+q)/2*i + (long long)A*(N-1-i*(D-2));
            if (count <= result) {
                break;
            }
            result = count;
        }
        printf("%lld\n", result);
    }
    return 0;
}
                        


                        Solution in C++ :

In  C ++  :





#include <bits/stdc++.h>
using namespace std;
#define fo(i,a,b) for(int i=(a);i<(b);i++)
#define MOD 1000000007
#define MT make_tuple
#define PB push_back
typedef long long ll;

int tst;
ll T, A, N, D, mx;

ll g (ll i, ll j) {
	return j*(j+1)/2 - i*(i-1)/2;
}

int main () {
	cin >> tst;
	while (tst--) {
		mx = -1;
		cin >> T >> A >> N >> D;
		if (D == 1) {
			cout << T*A << '\n';
			continue;
		}
		for (ll l = 0; l <= T; l++) {
			ll sum = 0;
			ll x = T-N+1, y = N-1;
			ll ls = A-(D-1), rs = D-1;
			if (ls * l < x) continue;
			if (rs * l > y) continue;

			ll lw = x / l; //this is how many full ones on left
			ll lrem = x - lw * l; //this is how many remain
			//from A-D+1-lw+1 to A-D+1, times l
			sum += g(A-D+1-lw+1, A-D+1) * l + lrem * (A-D+1-lw);
			sum += g(A-D+2, A-1) * l + (y - l * (D-2)) * A;
			mx = max(mx, sum);
		}
		if (mx == -1) cout << "SAD" << '\n';
		else cout << mx << '\n';
	}
	return 0;
}
                    


                        Solution in Java :

In   Java :






import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        for(int a0 = 0; a0 < T; a0++){
            int L = in.nextInt();
            long A = in.nextInt();
            int N = in.nextInt();
            int D = in.nextInt();

            if (N<D || N>L || A<D){
                System.out.println("SAD");
                continue;
            }

            // Deal with the special case
            if (D==1){
                System.out.println(L*A);
                continue;
            }

            // The number of accessories
            // A : a1
            // A-1 to A-n: a2
            // A-n-1: a3
            long max = 0;
            int a2Max = (N-1)/(D-1);
            // Loop start from maximun a2
            for (int a2=a2Max;a2>=1; a2--){
                // Calculate a1, a3, and n by a2
                long a1 = N + (a2-1) - a2*(D-1);        
                long n = (L-a1)/a2;
                long a3 = (L-a1)%a2;
                // Break when the type of accessories (A) is not enough
                if (n>A-1 || (n==A-1 && a3 > 0)){
                    break;
                }
                // Caclulate cost
               long sum = A*a1 + (A-1+A-n)*n/2*a2 + a3 * (A-n-1);
                // Break when cost starts decreasing
                if (sum<=max){
                    break;
                }
                max = sum;                    
            }            
            System.out.println(max==0?"SAD":max);
        }
    }
}
                    


                        Solution in Python : 
                            
In  Python3 :







import math

def total(g):
    # g = size of consecutive groups after the first one
    if g <= 0:
        return 0
    first = N - g * (D - 2) - 1
    f = (L - first) // g
    if first < g or A - f <= 0 or first + g * (A - 1) < L:
        return 0
    partial = int((2 * (A - 1) - f + 1) / 2 * f)
    left = (A - f - 1) * (-f * g + L - first)
    return first * A + partial * g + left

for _ in range(int(input())):
    L, A, N, D = map(int, input().strip().split())
    if D == 1:
        print(L * A)
        continue
    if D == 2:
        n1 = (N - 1)
        if n1 * A >= L:
            ln1 = L // n1
            print(int((2 * A + 1 - ln1) / 2 * ln1 * n1) + (A - ln1) * (L - ln1 * n1))
            continue
        else:
            print('SAD')
            continue
    if A == 1:
        print('SAD')
        continue
    if A == 2:
        if D == 2 and (N - D + 1) * 2 >= L:
            print(N - D + L + 1)
            continue
        else:
            print('SAD')
            continue

    g = math.ceil((L - A - N + D) / (A - 2))
    if g > N - D:
        print('SAD')
        continue
    else:
        # I did the math
        # ArgMax of total, A > 2 and D > 2
        argmax = int(math.sqrt((2 - 3 * D + D * D) * (1 + L - N) * (1 + L - N)) / (2 - 3 * D + D * D)) + 1
        if (D == 3 or D == 4 and A > 2) or (D > 4 and A > D - 2):
            # region where enough items are in A (A - f > 0)
            argmax = max(int((1 + L - N) / (2 + A - D)), argmax)
            # region where first group is the largest (first >= g)
            argmax = min(int((N - 1) / (D - 1)), argmax)
            # region where total number of items is at least L (first + g * (A - 1) >= L)
            if D == 3 or A > D - 1:
                argmax = max(int((1 + L - N) / (1 + A - D)), argmax)
            elif D > 3 and A < D - 1:
                argmax = min(int((1 + L - N) / (1 + A - D)), argmax)
        max_haul = max(total(argmax - 1), total(argmax), total(argmax + 1))
        print(max_haul if max_haul else 'SAD')
                    


View More Similar Problems

Balanced Forest

Greg has a tree of nodes containing integer data. He wants to insert a node with some non-zero integer value somewhere into the tree. His goal is to be able to cut two edges and have the values of each of the three new trees sum to the same amount. This is called a balanced forest. Being frugal, the data value he inserts should be minimal. Determine the minimal amount that a new node can have to a

View Solution →

Jenny's Subtrees

Jenny loves experimenting with trees. Her favorite tree has n nodes connected by n - 1 edges, and each edge is ` unit in length. She wants to cut a subtree (i.e., a connected part of the original tree) of radius r from this tree by performing the following two steps: 1. Choose a node, x , from the tree. 2. Cut a subtree consisting of all nodes which are not further than r units from node x .

View Solution →

Tree Coordinates

We consider metric space to be a pair, , where is a set and such that the following conditions hold: where is the distance between points and . Let's define the product of two metric spaces, , to be such that: , where , . So, it follows logically that is also a metric space. We then define squared metric space, , to be the product of a metric space multiplied with itself: . For

View Solution →

Array Pairs

Consider an array of n integers, A = [ a1, a2, . . . . an] . Find and print the total number of (i , j) pairs such that ai * aj <= max(ai, ai+1, . . . aj) where i < j. Input Format The first line contains an integer, n , denoting the number of elements in the array. The second line consists of n space-separated integers describing the respective values of a1, a2 , . . . an .

View Solution →

Self Balancing Tree

An AVL tree (Georgy Adelson-Velsky and Landis' tree, named after the inventors) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. We define balance factor for each node as : balanceFactor = height(left subtree) - height(righ

View Solution →

Array and simple queries

Given two numbers N and M. N indicates the number of elements in the array A[](1-indexed) and M indicates number of queries. You need to perform two types of queries on the array A[] . You are given queries. Queries can be of two types, type 1 and type 2. Type 1 queries are represented as 1 i j : Modify the given array by removing elements from i to j and adding them to the front. Ty

View Solution →