সংখ্যার একটি অ্যারে এবং একটি স্ট্যাক দেওয়া হয়েছে৷ অ্যারের সমস্ত উপাদান স্ট্যাকের ভিতরে উপস্থিত থাকে লক্ষ্য হল পৃথক অ্যারে উপাদানগুলি পাওয়ার জন্য প্রয়োজনীয় পপ অপারেশনগুলির গণনা খুঁজে বের করা৷
স্ট্যাকটি ক্রমহ্রাসমান ক্রমে পূর্ণ হয়, প্রথম উপাদানটি সর্বোচ্চ এবং শীর্ষ উপাদানটি সর্বনিম্ন৷
উদাহরণস্বরূপ
ইনপুট
Stack [ 7,6,2,1 ] array : 2,1,6,7
আউটপুট
Count of number of pop operations on stack to get each element of the array are: 3 1 0 0
ব্যাখ্যা
Traversing array from 0th index, To get 2 we will pop stack three times. So arr[0] is 3. First two pops will give 7 and 6 also. To get 1 we will pop stack once now. So arr[1] is 1. For 6 and 7 as these are already popped, so arr[2]=arr[3]=0.
ইনপুট
Stack [ 3,2,1,1 ] array : 1,2,1,3
আউটপুট
Count of number of pop operations on stack to get each element of the array are: 3 0 1 0
ব্যাখ্যা
Traversing array from 0th index, To get 1 we will pop stack three times. So arr[0] is 3. First two pops will give 3 and 2 also.Traversing array from 0th index, To get 1 we will pop stack three times. So arr[0] is 3. First two pops will give 3 and 2 also.
নিম্নলিখিত প্রোগ্রামে ব্যবহৃত পদ্ধতি −
এই পদ্ধতিতে আমরা একটি unordered_map
-
একটি পূর্ণসংখ্যা অ্যারে arr[] নিন।
-
এটিতে উপাদান সংরক্ষণের জন্য একটি স্ট্যাক
stck নিন। -
এটিতে উপাদানগুলিকে হ্রাসকারী ক্রমে পুশ করুন৷
৷ -
ফাংশন pop_operations(stack
&stck, int arr[], int উপাদান) অ্যারের প্রতিটি উপাদান পেতে স্ট্যাকের পপ অপারেশনের সংখ্যা প্রদান করে। -
0 হিসাবে প্রাথমিক গণনা নিন।
-
স্ট্যাকের পপ অপারেশন করার সময় সম্মুখীন হওয়া অনন্য সংখ্যাগুলি সংরক্ষণের জন্য unordered_map
um নিন৷ -
লুপের জন্য ব্যবহার করে ট্রাভার্স অ্যারে।
-
temp=arr[i] নিন।
-
যদি তাপমাত্রা উমে না থাকে। এটি পেতে 0 পপ অপারেশন প্রিন্ট করুন।
-
অন্যথায় যখন টেম্প পাওয়া যায় না, স্ট্যাকের উপর পপ করুন এবং উমে পপ করা প্রতিটি উপাদানকে সত্য এবং বৃদ্ধির সংখ্যা হিসাবে সেট করুন।
-
সময়ের শেষে, প্রিন্ট গণনা।
-
এইভাবে আমরা অ্যারের প্রতিটি উপাদানের জন্য পপ অপারেশনের সংখ্যা প্রিন্ট করব।
উদাহরণ
#include <bits/stdc++.h>
using namespace std;
void pop_operations(stack<int>& stck, int arr[], int elements){
int count = 0;
unordered_map<int, bool> um;
cout<<"Count of number of pop operations on stack to get each element of the array are: ";
for (int i = 0; i < elements; ++i){
int temp = arr[i];
if (um.find(temp) != um.end())
{ cout << "0 "; }
else{
count = 0;
while (stck.top() != temp){
um[stck.top()] = true;
stck.pop();
count++;
}
stck.pop();
count++;
cout<<count<<" ";
}
}
}
int main(){
int elements = 4;
int arr[] = { 2, 1, 6, 7};
stack<int> stck;
stck.push(1);
stck.push(2);
stck.push(6);
stck.push(7);
pop_operations(stck, arr, elements);
return 0;
} আউটপুট
যদি আমরা উপরের কোডটি চালাই তবে এটি নিম্নলিখিত আউটপুট −
উৎপন্ন করবেCount of number of pop operations on stack to get each element of the array are: 3 1 0 0