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

Tree: Height of a Binary Tree

The height of a binary tree is the number of edges between the tree's root and its furthest leaf. For example, the following binary tree is of height : image Function Description Complete the getHeight or height function in the editor. It must return the height of a binary tree as an integer. getHeight or height has the following parameter(s): root: a reference to the root of a binary

View Solution →

Tree : Top View

Given a pointer to the root of a binary tree, print the top view of the binary tree. The tree as seen from the top the nodes, is called the top view of the tree. For example : 1 \ 2 \ 5 / \ 3 6 \ 4 Top View : 1 -> 2 -> 5 -> 6 Complete the function topView and print the resulting values on a single line separated by space.

View Solution →

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →