代码改变世界

POJ 3750 小孩报数问题

2012-02-23 12:30  咆哮的马甲  阅读(218)  评论(0编辑  收藏  举报

基本的双向链表即可实现。

最后一个element的判定很重要。

 

#include <iostream>
#include <string>

using namespace std;

typedef struct Child
{
string name;
Child* pre;
Child* next;
} Child;


int main()
{
// Get input N
int n;
cin>>n;

Child* head = NULL;
Child* tail = NULL;
Child* cur = NULL;

// Create dlink list
for(int i=0; i<n; i++)
{
cur = new Child();
cin>>cur->name;
if(head == NULL)
{
head = cur;
tail = cur;
cur->next = cur;
cur->pre = cur;
}
else
{
head->pre = cur;
tail->next = cur;
cur->pre = tail;
cur->next = head;
tail = cur;
}
}

cur = head;
int w,s;

cin>>w;
cin.get(); // ignore comma
cin>>s;

// get the W-th element
if(cur != NULL)
{
while(w-1 != 0)
{
cur = cur->next;
w--;
}
}

// output the child who says "S"
while(cur != NULL)
{
int tmp = s;
while(tmp-1 != 0)
{
cur = cur->next;
tmp--;
}

cout<<cur->name<<"\n";
if(cur->pre == cur && cur->next == cur) // the last element
break;
cur->pre->next = cur->next;
cur->next->pre = cur->pre;
Child* head = cur->next;
delete cur;
cur = head;

}

return 0;
}