2015年7月29日 星期三

[UVA] 133 - The Dole Queue

題意:
給你N個數,A和B兩個人在數數,A往右邊數k個,B往左邊數m個,
每一回合輸出被A和B數到的數並刪除。
例如:
有10 個數,A往右邊數4個,B往左邊數3個,
1 2 3 4 5 6 7 8 9 10
         ^         ^
         A        B
第一回合就輸出4 8
注意: B往左邊數小於0就從尾巴繼續數吧

解題:
開一維陣列,設定兩個指標posR和posL分別往右往左一個一個數吧,
數到的把它變成-1,下次數的時候就跳過。
小技巧:
讓posR和posL不超出陣列範圍,
把posL加上陣列大小之後再mod就可以了!
例如:
現在陣列大小10,
posL現在指到-1位置,
可是陣列沒有-1的這個位置,
就將(posL+10)%10變成9
讚讚

/* 20150729
 * hanting
 * UVa 133 - The Dole Queue
 * C++
 */
#include <iostream>
#include <vector>
#include <iomanip>//setw
using namespace std;
int main()
{
    int manN,right,left;//往右k//往左m
    while(cin>>manN>>right>>left and manN)
    {
        int posR=-1,posL=0;
        vector<int> vec(manN);
        for(int i=0;i<manN;i++)
        {
            vec[i]=i+1;
        }
        int cnt=0;
        while(cnt<vec.size())//數到陣列元素都變-1
        {
            for(int i=0;i<right;i++)//往右走
            {
                posR++;
                posR%=manN;
                if(vec[posR]==-1) i--;
            }
            for(int i=0;i<left;i++)//往左走
            {
                posL--;
                posL=(posL+manN)%manN;
                if(vec[posL]==-1) i--;
            }
            if(posR==posL)
            {
                cnt++;
                cout<<setw(3)<<vec[posR]<<(cnt<vec.size() ? ",":"");
            }
            else
            {
                cnt+=2;
                cout<<setw(3)<<vec[posR]<<setw(3)<<vec[posL]<<(cnt<vec.size() ? ",":"");
            }
            vec[posR]=vec[posL]=-1;
        }
        cout<<endl;
    }
    return 0;
}

沒有留言:

張貼留言