【例题4-3 uva 133】The Dole Queue

【链接】 我是链接,点我呀:)
【题意】


在这里输入题意

【题解】


写个数组模拟链表
但注意,得用个辅助数组flag。。
不然可能会出现没能跳过中间的被占区域的情况。
比如
1 2 idx # # # idx2 8
(#表示已经出去的位置)
这个时候,idx1和idx2删掉的话。(假设先删idx1,后删idx2)
r[idx1]无法更新为8。。

【代码】

#include <bits/stdc++.h>
using namespace std;

const int N = 20;

int n,m,k;

int l[N+10],r[N+10];
int flag[N+10];

void _delete(int idx){
    int L = l[idx],R = r[idx];
    r[L] = R;
    l[R] = L;
}

void step_left(int *x){
    *x = l[*x];
    while (flag[*x]) *x =l[*x];
}

void step_right(int *x){
    *x = r[*x];
    while (flag[*x]) *x=r[*x];
}

int main()
{
    //freopen("/home/ccy/rush.txt","r",stdin);
    ios::sync_with_stdio(0),cin.tie(0);
    while (cin >> n >> k >> m){
        memset(flag,0,sizeof flag);
        if(n==0 && m==0 && k==0) break;
        int idx1 = 1,idx2 = n;
        for (int i = 1;i <= n;i++) l[i] = i-1,r[i]=i+1;
        l[1] = n;r[n] = 1;
        int cnt = n;
        while (cnt>0){
            for (int i = 1;i <= k-1;i++) step_right(&idx1);
            for (int i = 1;i <= m-1;i++) step_left(&idx2);
            if (idx1==idx2){
                _delete(idx1);
                cnt--;
                cout<<setw(3)<<idx1;
            }else{
                _delete(idx1);_delete(idx2);
                while (flag[idx1]) idx1 = r[idx1];
                while (flag[idx2]) idx2 = l[idx2];
                cnt-=2;
                cout<<setw(3)<<idx1<<setw(3)<<idx2;
            }
            flag[idx1] = flag[idx2]=1;
            if (cnt==0) {
                cout<<endl;
                break;
            }else cout<<",";
            step_right(&idx1);step_left(&idx2);
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/AWCXV/p/9834502.html
133