I m getting TLE. Please suggest any changes or a different approach.
Importance of time problem
hello @apoorvas1301
refer this approach->
- The Idea is to Store the Calling order in Queue and the ideal order in an Array.
- Then compare front element of the queue with the ideal order.
- If it matches then increment the time and remove the element.
- Else, Dequeue the element and enqueue it again.
- The loop will run till the queue is consumed totally.
code implementation->
#include <bits/stdc++.h>
using namespace std;
int importanceOfTime(queue<int> &q, const vector<int> &arr)
{
//arr is the ideal order
//q is the calling order
int ans = 0;
for (int i = 0; i < arr.size(); i++)
{
if (q.front() == arr[i])
{
ans++;
q.pop();
}
else
{
while (q.front() != arr[i])
{
int var = q.front();
q.push(var);
q.pop();
ans++;
}
ans++;
q.pop();
}
}
return ans;
}
int main()
{
int n;
cin >> n;
vector<int> v(n);
queue<int> q;
for (int i = 0; i < n; i++)
{
int x;
cin >> x;
q.push(x);
}
for (int i = 0; i < n; i++)
{
cin >> v[i];
}
cout << importanceOfTime(q, v);
return 0;
}
Thank you. Can you also point out the errors in my code?
yeah , pls explain ur approach , i will try to debug it
@apoorvas1301
check ur updated code here->
#include<iostream>
#include<deque>
using namespace std;
int timerequired(deque<int> &q1,deque<int> &q2,int n)
{
int count=0;
while(n--)
{
while(q1.front()!=q2.front())
{
int x=q1.front();
q1.pop_front();
q1.push_back(x); // u were pushing it to q2
count++;
}
// removed : count++;
if(q1.front()==q2.front())
{
count++;
q1.pop_front();
q2.pop_front();
}
}
return count;
}
int main() {
int n,a,b;
cin>>n;
int k=n;
deque<int> q1,q2;
while(n--)
{
cin>>a;
q1.push_back(a);
}
n=k; // after this loop n will be zero so u need to again reinitilaise
while(n--)
{
cin>>b;
q2.push_back(b);
}
cout<<timerequired(q1,q2,k)<<endl;
return 0;
}
It worked .Thank you