What is the complexity of this program

I solved the issue of HackerEarth. Question:

Phineas is building a castle in the backyard to impress Isabella (strange, isn't it?). He has everything ready and ready. Even the first floor was finished. Now it's time to make the top. Everything becomes interesting here. When Ferb slept in the house after a long day, drawing a fence (and you guys helped him, not me!), Phineas must do all the work himself. He is good at it, and all he wants from you is to operate a mini-crane to raise stones. The stones for the wall were cut off and ready to wait until you pick them up.

Now we do not have Ferb to operate a mini-crane, in which he is an expert, we must do the job as quickly as possible. We are given the maximum lifting capacity of the crane and the weight of each stone. Since this is a mini-crane, we cannot place more than two stones (of any possible size) at a time, otherwise it will upset the balance of the crane. we need to find out how many moves we can deliver to the stones of Phineas, who builds the castle.

INPUT: The first line of input gives T, the number of test cases. For each test case, the first line gives M the maximum crane capacity. the first integer N of the next line of each test case gives the number of stones, followed by N numbers that determine the weight of an individual stone X.

OUTPUT: for each test case, print the minimum number of turns the cranes operate on for all stones removed.

DIFFICULTIES:

1 <= T <= 50
1 <= M <= 1000
1 <= N <= 1000

1
50
3 28 22 48

2

28 22 . 48 . > .

,

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace std;


int main(void) {
    int T = 0;
    scanf("%d",&T);
    while(T--) {
        int i = 0,M = 0, N = 0,max = 0, res = 0, index = 0, j = 0, temp = 0;
        vector<int> v1;
        scanf("%d",&M);
        scanf("%d",&N);
        for(i = 0; i < N ;++i) {
            scanf("%d",&temp);
            if(temp <= M)
                v1.push_back(temp);
        }

        for(i = 0; i < v1.size() ; ++i) {
            max = 0;
            index = 0;
            if(v1[i] != -1) {
                for(j = i + 1; j < v1.size(); ++j) {
                    if(v1[j] != -1) {
                        temp = v1[i] + v1[j];
                        if(temp > max && temp <= M) {
                            max = temp;
                            index = j;
                        }
                    }
                }
                ++res;
                v1[i] = -1;
                v1[index] = -1;
            }
        }

        printf("%d\n",res);
    }

    return 0;

}

  • . , O (N ^ 2).
  • ?
  • ?
+4
1

Knapsack Prolblem

Knapsack , . O (n ^ 2), Greedy , . O (nlgn), .

+2

All Articles