题目来自洛谷社区:
我的第一种做法,用C++库里面的list,还有算法库里的find函数,感觉代码很简单,但是通过不了,运行超时。
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
list<int> a;
a.push_back(1);
int m;
int lo,st;
cin >> m;
list<int>::iterator it;
for(int i = 2;i<= m;i++)
{
cin >> lo >> st;
it = find(a.begin(),a.end(),lo);
if(st == 0)
a.insert(it,i);
else
a.insert(++it,i);
}
int n,x;
cin >> n;
for( int i = 1; i<=n;i++)
{
cin >> x;
it = find(a.begin(),a.end(),x);
if(it == a.end())
continue;
a.erase(it);
}
for(it = a.begin();it!=a.end();it++)
{
cout << *it<<' ';
}
cout << endl;
return 0;
}
所以想想还是要找一下第二种方法:
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
struct N
{
int no;
N *next;
N *front;
}node[100000];
int main()
{
int m;
cin >> m;
N *head = NULL;
N *tail = NULL;
for(int i = 1; i<=m;i++)
{
node[i].no = i;
node[i].next = NULL;
node[i].front = NULL;
}
int lo,st;
head = &node[1];
for(int i = 2; i <= m ;i++)
{
cin >> lo >> st;
if(st == 0)
{
if(&node[lo] == head)
{
head->front = &node[i];
node[i].next = head;
head = &node[i];
}
else
{
node[lo].front->next = &node[i];
node[i].front = node[lo].front;
node[i].next = &node[lo];
node[lo].front = &node[i];
}
}
else
{
if (node[lo].next == NULL)
{
node[lo].next = &node[i];
node[i].front = &node[lo];
node[i].next = NULL;
}
else
{
node[i].next = node[lo].next;
node[i].next->front = &node[i];
node[lo].next = &node[i];
}
}
}
int n,x;
cin >> n;
N *p2;
for(int i =1;i<=n;i++)
{
cin >> x;
N *p2 = &node[x];
if (p2)
{
if ( node[x].no == head->no)
head = node[x].next;
else
{
node[x].front ->next = node[x].next;
node[x].next->front= node[x].front;
}
free(p2);
}
}
N *p = head;
while(p)
{
cout << p->no;
cout<<endl;
p = p->next;
}
return 0;
}