This is an easy problem from uva judge http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=3359
Data structures, Linked List.
How I did it
- I read the number of elements and queries.
- If the number of elements is equal or less than 1000 I push the number of element into a linked list, otherwise I push 1000 elements.
- Read the queries, if the querie is “N” print the front element of the list and pop the element and push it into the tail. If the querie is “E” read the value, remove the value from the list and push in the front of the list.
Hints
- When the querie is E I dont print any value.
- I initialize the list at most 1000 elements because the number of queries are 1000, and the idea is handle a queue.
- If you initialize the linked list, deque or queue with 1000000000 you will get time limit.
Code
#include <algorithm> #include <iostream> #include <cstdio> #include <list> using namespace std; list<int> lista; void init(int N) { lista.clear(); int lim = min(N, 1000); for(int i=1; i<=lim; i++) lista.push_back(i); } int main() { int dim, queries, pos, tmp, casos = 1; char ins; while(scanf("%d %d", &dim, &queries)) { if(!dim && !queries) break; init(dim); printf("Case %d:\n", casos++); for(int i=1; i<=queries; i++) { cin>>ins; if(ins == 'N') { tmp = lista.front(); printf("%d\n", tmp); lista.pop_front(); //if(dim <= 1000) lista.push_back(tmp); } else { scanf("%d", &pos); lista.remove(pos); lista.push_front(pos); } } } return 0; }