uva 133 - The Dole Queue

来源:互联网 发布:关于汽车修理的软件 编辑:程序博客网 时间:2024/05/04 07:06

数据结构,双向链表。

一个人从第一个开始逆时针数,一个人从最后一个开始顺时针数,数到的人出去,如果是同一个人则只有那一个人出去。

构建链表时注意,如果数的两个人相邻的话,则连接链表时不能直接连数的那人左右两边的人。

#include<cstdio>#include<cstring>const int MAXN=30;int right[MAXN];int left[MAXN];void link(int a,int b){             //连接函数    right[a]=b;    left[b]=a;}int main(){   // freopen("in.txt","r",stdin);   // freopen("out.txt","w",stdout);    int N,k,m;    while(~scanf("%d%d%d",&N,&k,&m)){        if(N==0||k==0||m==0) break;        memset(left,0,sizeof(left));        memset(right,0,sizeof(right));        for(int i=1;i<=N;i++){              //初始化链表            right[i]=i+1;            left[i]=i-1;        }        right[N]=1;left[1]=N;               //首尾相连        int i,j;        int temp1=1,temp2=N,counter=0;        while(1){            for(i=1;i<k;i++) temp1=right[temp1];        //判断第一个人数的位置的值            for(j=1;j<m;j++) temp2=left[temp2];         //第二个人数的位置的值            if(temp1==temp2){                           //若为同一个位置                printf("%3d",temp1);                counter++;                link(left[temp1],right[temp1]);                temp1=right[temp1];                temp2=left[temp2];            }            else if(right[temp1]==temp2){               //为相邻的位置                printf("%3d%3d",temp1,temp2);                counter+=2;                link(left[temp1],right[temp2]);                temp1=right[temp2];                temp2=left[temp1];            }            else if(left[temp1]==temp2){                printf("%3d%3d",temp1,temp2);                counter+=2;                link(left[temp2],right[temp1]);                temp1=right[temp1];                temp2=left[temp2];            }            else{                               //位置至少相隔一个人                printf("%3d%3d",temp1,temp2);                counter+=2;                link(left[temp1],right[temp1]);                temp1=right[temp1];                link(left[temp2],right[temp2]);                temp2=left[temp2];            }            if(counter!=N) printf(",");            else break;        }        printf("\n");    }    return 0;}


 

 

0 0
原创粉丝点击