Time Limit Exceed 小球移动Description有一排小球,自左至右依次编号为1,2,3,...,n,可执行两种指令移动小球,L X Y表示将小球X移到小球Y的左边,R X Y表示将小球X移到小球Y的右边,保证X!=Y.输入小球的个数
来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/20 01:03:40
Time Limit Exceed 小球移动Description有一排小球,自左至右依次编号为1,2,3,...,n,可执行两种指令移动小球,L X Y表示将小球X移到小球Y的左边,R X Y表示将小球X移到小球Y的右边,保证X!=Y.输入小球的个数
Time Limit Exceed 小球移动
Description
有一排小球,自左至右依次编号为1,2,3,...,n,可执行两种指令移动小球,L X Y表示将小球X移到小球Y的左边,R X Y表示将小球X移到小球Y的右边,保证X!=Y.输入小球的个数n,指令的条数m和对应的m条指令,请输出最后小球的顺序(提示:n可能高达500000,m可能高达1000000).
Input
小球个数和指令的条数,对应的具体指令
有多组数据
Output
最后小球的顺序
Sample Input
6 2
L 1 4
R 3 5
Sample Output
2 1 4 5 3 6
#include
#include
#define MAXBALL 500000
#define MAXCOM 100000
typedef struct ball
{
int num;
struct ball *next;
} Ball;
Ball* create(int n)
{
int i;
Ball *head,*p,*q;
head = (Ball*) malloc (sizeof(Ball));
head->num = 0;
head->next = NULL;
q = head;
for (i = 0; i < n; i++){
p = (Ball*) malloc (sizeof(Ball));
p->num = i+1;
q->next = p;
q = p;}
q->next = NULL;
return head;
}
Ball* move(Ball* head,int m)
{
int i,x,y;
char com;
Ball *px,*prex,*py,*prey;
for (i=0; i < m; i++)
{
prex = prey = head;
px = prex->next;
py = prey->next;
scanf ("\n%c%d%d",&com,&x,&y);
if (x == y){
exit (1);
}
else
{
while (px->num = x)
{
prex = px;
px = prex->next;
}
while (py->num = y)
{
prey = py;
py = prey->next;
}
if (com == 'L')
{
prex->next = px->next;
prey->next = px;
px->next = py;
}
else if (com == 'R')
{
prex->next = px->next;
px->next = py->next;
py->next = px;
}
}
}
return head;
}
void destroy(Ball* head,int n)
{
int i;
Ball *p;
for (i = 1; i < n ; i++)
{
p = head;
head = head->next;
free (p);
}
free(head);
}
void show(Ball* head)
{
Ball *p;
p = head->next;
while (p)
{
printf ("%d ",p->num);
p = p->next;
}
printf ("\n");
}
int main()
{
int x,y;
char com;
int n,m;
while(scanf ("%d%d",&n,&m) = EOF){
if (n > MAXBALL || m > MAXCOM)
exit (1);
Ball* head = create(n);
move(head,m);
show(head);
destroy(head,n);
}
return 0;
}
为什么Time Limit Exceed 怎么修改呢
Time Limit Exceed 小球移动Description有一排小球,自左至右依次编号为1,2,3,...,n,可执行两种指令移动小球,L X Y表示将小球X移到小球Y的左边,R X Y表示将小球X移到小球Y的右边,保证X!=Y.输入小球的个数
#include
const int MAX=500005;
struct NODE
{
int l,r;
}node[MAX];
int main()
{
//用链用做,你的每次查找复杂度是O(n)我的是O(1)
int n,m,i,j,l,r;
char cmd[10];
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=1;i