问题描述
体育老师小明要将自己班上的学生按顺序排队。他首先让学生按学号从小到大的顺序排成一排,学号小的排在前面,然后进行多次调整。一次调整小明可能让一位同学出队,向前或者向后移动一段距离后再插入队列。
例如,下面给出了一组移动的例子,例子中学生的人数为8人。
0)初始队列中学生的学号依次为1, 2, 3, 4, 5, 6, 7, 8;
1)第一次调整,命令为“3号同学向后移动2”,表示3号同学出队,向后移动2名同学的距离,再插入到队列中,新队列中学生的学号依次为1, 2, 4, 5, 3, 6, 7, 8;
2)第二次调整,命令为“8号同学向前移动3”,表示8号同学出队,向前移动3名同学的距离,再插入到队列中,新队列中学生的学号依次为1, 2, 4, 5, 8, 3, 6, 7;
3)第三次调整,命令为“3号同学向前移动2”,表示3号同学出队,向前移动2名同学的距离,再插入到队列中,新队列中学生的学号依次为1, 2, 4, 3, 5, 8, 6, 7。
小明记录了所有调整的过程,请问,最终从前向后所有学生的学号依次是多少?
请特别注意,上述移动过程中所涉及的号码指的是学号,而不是在队伍中的位置。在向后移动时,移动的距离不超过对应同学后面的人数,如果向后移动的距离正好等于对应同学后面的人数则该同学会移动到队列的最后面。在向前移动时,移动的距离不超过对应同学前面的人数,如果向前移动的距离正好等于对应同学前面的人数则该同学会移动到队列的最前面。
输入格式
输入的第一行包含一个整数n,表示学生的数量,学生的学号由1到n编号。
第二行包含一个整数m,表示调整的次数。
接下来m行,每行两个整数p, q,如果q为正,表示学号为p的同学向后移动q,如果q为负,表示学号为p的同学向前移动-q。
输出格式
输出一行,包含n个整数,相邻两个整数之间由一个空格分隔,表示最终从前向后所有学生的学号。
样例输入
8
3
3 2
8 -3
3 -2
样例输出
1 2 4 3 5 8 6 7
评测用例规模与约定
对于所有评测用例,1 ≤ n ≤ 1000,1 ≤ m ≤ 1000,所有移动均合法。
解题思路:属于模拟题,但第一次做的时候没有仔细思考,错误判断数组中元素移动会导致超时,所以采用链表做,在没有容器的的情况下还是相当麻烦的,尤其是头和尾的插入,我这样做虽然对了但很麻烦,权当练习一次链表建立删除插入了233.
建议直接使用数组,时间复杂度为1e6,不会超时而且好读。
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
#define M 1002
typedef struct node{
int num;
struct node *pre;
struct node *next;
}que;//
int n,m;
que *head;
que* creat(){
que * lst=(que*)malloc(sizeof(struct node));
que * hed=lst,*pret=lst;
lst->pre=lst->next=NULL;
lst->num=1;
for(int i=2;i<=n;i++){
lst=(que*)malloc(sizeof(struct node));
lst->pre=pret;
lst->num=i;
pret->next=lst;
lst->next=NULL;
pret=lst;
}
return hed;
}
que* find(int a){
que* p=head;
while(p){
if(p->num==a){
return p;
}
p=p->next;
}
}
void change(que * a,que *b){
que* tmp;
if(a->pre) //若不判定,第一个节点后调时会出错
a->pre->next=a->next;
else
head=a->next;
if(a->next) //若不判定,最后一个节点前调时会出错
a->next->pre=a->pre;
if(b->pre){//当某个节点插入第一个位置时。
b->pre->next=a;
}
else
head=a;
a->pre=b->pre;
a->next=b;
b->pre=a;
}
int main(){
cin>>n>>m;
head=creat();
que* pos=head;
for(int i=0;i<m;i++){
int p,q;
cin>>p>>q;
que* locp=find(p);
que* locq=locp;
if(q>0){
q++;
while(q&&locq->next){
locq=locq->next;
q--;
}
if(q){
if(locp->pre)
locp->pre->next=locp->next;
else
head=locp->next;
if(locp->next)
locp->next->pre=locp->pre;
locp->next=NULL;
locp->pre=locq;
locq->next=locp;//cout<<"**"<<locq->num<<endl;
}
else
change(locp,locq);
}
else{
q*=-1;
while(q&&locq){
locq=locq->pre;
q--;
}
change(locp,locq);
}
//
}
pos=head;
que* pre=pos;
while(pos){
cout<<pos->num<<" ";
pre=pos;
pos=pos->next;
free(pre);
}
cout<<endl;
return 0;
}
第二遍做明显清晰了许多,stl中的容器真的很省时间。
#include<iostream>
#include<vector>
using namespace std;
vector <int > vec;
int find(int a){
for(int i=0;i<vec.size();i++){
if(vec[i]==a){
return i;
}
}
return -1;
}
int main(){
int n;
int m;
cin>>n>>m;
for(int i=1;i<=n;i++){
vec.push_back(i);
}
for(int i=0;i<m;i++){
int a,b;
cin>>a>>b;
int pos=find(a);
int de=pos+b;
vec.erase(vec.begin()+pos,vec.begin()+pos+1);
vec.insert(vec.begin()+de,a);
}
for(int i=0;i<vec.size();i++){
cout<<vec[i]<<" ";
}
return 0;
}