我一直在尝试使用循环双向链表来实现这个问题。 http://www.spoj.com/problems/CLSLDR/
我的代码超出了时间限制。有人可以指出我正在做的错误吗?
我使用O(n)算法在删除每个第p个元素后识别最后一个元素。
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
void deleteNode( struct Node* ptr ) {
ptr->prev->next = ptr->next;
ptr->next->prev = ptr->prev;
delete ptr;
}
int main() {
ios_base::sync_with_stdio( false );
int t, n, m, p, i;
cin >> t;
while( t-- ) {
cin >> n >> m >> p;
struct Node* root = new Node;
root->data = 1;
struct Node* head = root;
struct Node* nxt = NULL;
for( i = 1;i < n;i++ ) {
head->next = new Node;
head->next->data = i + 1;
head->next->prev = head;
head = head->next;
}
head->next = root;
root->prev = head;
head = root;
for( i = 1;i < m;i++ ) {
head = head->next;
}
i = 1;
while( n != 1 ) {
for( ;i <= p;i++ ) {
head = head->next;
}
nxt = head->next;
deleteNode( head );
head = nxt;
i = 2;
n--;
}
cout << head->data << "\n";
}
return 0;
}
答案 0 :(得分:0)
我想对于给定的约束,O(n)方法绑定到TLE。您的方法将采用T * n(10 ^ 6 * 10 ^ 3),即10 ^ 9个运算。极限是0.699s,甚至1s都不够。