首页 > 代码库 > UVA - 133 The Dole Queue(模拟链表)

UVA - 133 The Dole Queue(模拟链表)

点击打开链接

n的人围成一个环,然后按逆时针编号1-n,一个人从1开始逆时针数k个数,另一个人从N开始顺时针数m个数,然后 数出来的两个人出列(两个人可能一样)出列,然后继续此过程,直到全部人都出列为止。

思路是用循环链表来模拟,注意 要分情况来讨论。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <cstring>
#include <string>
#include <algorithm>
#include <string>
#include <set>
#include <functional>
#include <numeric>
#include <sstream>
#include <stack>
#include <map>
#include <queue>

#define CL(arr, val)    memset(arr, val, sizeof(arr))

#define ll long long
#define inf 0x7f7f7f7f
#define lc l,m,rt<<1
#define rc m + 1,r,rt<<1|1
#define pi acos(-1.0)

#define L(x)    (x) << 1
#define R(x)    (x) << 1 | 1
#define MID(l, r)   (l + r) >> 1
#define Min(x, y)   (x) < (y) ? (x) : (y)
#define Max(x, y)   (x) < (y) ? (y) : (x)
#define E(x)        (1 << (x))
#define iabs(x)     (x) < 0 ? -(x) : (x)
#define OUT(x)  printf("%I64d\n", x)
#define lowbit(x)   (x)&(-x)
#define Read()  freopen("a.txt", "r", stdin)
#define Write() freopen("dout.txt", "w", stdout);
#define N 100005
using namespace std;
int n,k,m,l[25],r[25];
void init()
{
    int i;
    for(i=1;i<=n;i++)
    {
        l[i]=i-1;
        r[i]=i+1;
    }
    r[n]=1;l[1]=n;
}
void link(int x,int y)
{
    l[y]=x; r[x]=y;
}

int main()
{
    //Read();
    int i,j,t,x,y,c1,c2;
    while(scanf("%d%d%d",&n,&k,&m)!=EOF&&n+k+m)
    {
        init();
        t=0;
        x=1;y=n;
        c1=c2=1;
        while(t<n)
        {
            //if(t) printf(",");
            if(c1==k&&c2==m)
            {
                if(x==y)
                {
                    printf("%3d",x);
                    x=r[x];
                    y=l[y];
                    link(y,x);
                    t++;
                }
                else if(r[x]==y)
                {
                    printf("%3d%3d",x,y);
                    x=r[r[x]];
                    y=l[l[y]];
                    link(y,x);
                    t+=2;
                }
                else if(r[y]==x)
                {
                    printf("%3d%3d",x,y);
                    x=r[x];
                    y=l[y];
                    link(y,x);
                    t+=2;
                }
                else
                {
                    printf("%3d%3d",x,y);
                    x=r[x];
                    y=l[y];
                    link(l[l[x]],x);
                    link(y,r[r[y]]);
                    t+=2;
                }
                //printf("%d %d\n",x,y);
                c1=c2=1;
                if(t!=n) printf(",");
            }
            if(c1!=k) {c1++;x=r[x];}
            if(c2!=m) {c2++;y=l[y];}
        }
        printf("\n");
    }
    return 0;
}


 

UVA - 133 The Dole Queue(模拟链表)