+ 2
way to learn!!
i was solving problem on codeforce and faced a new input method to me (sequence of numbers separated by spaces) and failed to solve it, i searched for the solution and found it:: #include <iostream> #include <algorithm> using namespace std; int main(){ int n, k; cin >> n >> k; int *scores = new int[n]; for(int u = 0; u < n; ++u){cin >> scores[u];} sort(scores, scores + n); int min = scores[n - k]; int promoted = 0; while(promoted < n && scores[n-1 - promoted] > 0 && scores[n-1 - promoted] >= min){++promoted;} cout << promoted << endl; return 0; } *** i know that my weak understanding is the cause but can any one describe the action of this code to me??
2 Respuestas
0
"int n, k; cin >> n >> k;"
This part can really be split up in for different lines to make it slightly easier to read:
int n;
int k;
cin >> n;
cin >> k;
This defines to integer variables and then asks the user to input to integers, storing the first in "n" and the second in "k".
"int *scores = new int[n];"
This defines an integer pointer that dynamically allocates memory via the "new" keyword for an integer array of size "n" (the first user input integer).
"for(int u = 0; u < n; ++u) {
cin >> scores[u];
}"
This for loop iterates through each spot in scores (the integer array) and asks the user to enter a number to put in each spot.
"sort(scores, scores + n);"
sort is a method included in the artay class the takes the starting and ending index of the array you want sorted, and sorts them from smallest to largest.
"int min = scores[n - k];"
defines an integer "min" as the value at index "n-k" in the scores array.
"int promoted = 0;"
Defines a new integer "promoted" with a value of 0.
0
"while(promoted < n && scores[n - 1 - promoted] > 0 && scores[n - 1 - promoted] >= min) {
++promoted;
}
This piece of code is essentially starting at the back of the array (scores[n - 1 - (0)]) and increasing "promoted" by 1 until it reaches a value that is either less than 0 (scores[n - 1 - promoted] > 0) or less than or equal to min (scores[n - 1 - promoted] >= min).
"cout << promoted << endl;"
prints out the value of promoted.
"return 0;"
ends the main method.
I apologize for going literally line by line, but i was not sure what you do and do not already know.