PAT_甲級_1042 Shuffling Machine

題目大意:

有54張牌,編號爲1~ 54,初始按編號從小到大排列。另外,這些牌按初始排列給定花色,即從左至右分別爲13張S、13張H、13張C、13張D、2張J,以下所示:算法

S1, S2.., S13, H1, H2,.., H13, C1, C2,..,CI3, D1, D2,., D13,J1,J2

接下來執行一種操做, 這種操做將牌的位置改變爲指定位置。例若有5張牌S3, H5, C1,D13, J2,而後給定操做序列{4,2, 5,3,1},所以把S3放到4號位、把H5放到2號位、C1放到5號位、D13 放到3號位、J2放到1號位,因而就變成了J2, H5, D13, S3, C1。如今須要將這種操做執行K次,求最後的排列結果。例如上面的例子中,若是執行第二次操做,那麼序列J2, H5, D13, S3,C1就會變成C1, HS, S3, J2, D13.數組

算法思路:

題目要求模擬洗牌過程,給定初始牌組爲cards,起始下標位置從1開始,給定洗牌順序orders,和洗牌次數K,要求得出最終洗牌結果。
題目比較簡單,就是使用hash的思想,咱們每次洗牌就建立一個新的數組new_cards暫存最終洗牌結果,該數組的值取決於orders與cards,
其對應關係爲new_cards[orders[j]] = cards[j];在new_cards數組求解完畢後,將new_cards數組賦值給cards便可,每次循環執行該過程,直到結束spa

提交結果:

圖片.png

AC代碼:
#include<cstdio>
#include<string>

using namespace std;

string cards[55]={"","S1", "S2", "S3","S4","S5","S6","S7","S8","S9","S10","S11","S12","S13",
                        "H1","H2","H3","H4","H5","H6","H7","H8","H9","H10","H11","H12","H13",
                        "C1","C2","C3","C4","C5","C6","C7","C8","C9","C10","C11","C12","C13",
                        "D1","D2","D3","D4","D5","D6","D7","D8","D9","D10","D11","D12","D13","J1","J2"};

int main(){
    int K;//重複次數
    scanf("%d",&K);
    int orders[55];
    for(int j=1;j<55;++j){
        scanf("%d",&orders[j]);
    }
    for(int i=0;i<K;++i){
        string new_cards[55];
        for(int j=1;j<55;++j){
            new_cards[orders[j]] = cards[j];
        }
        // 將new_cards的值賦值給cards
        for(int j=1;j<55;++j){
            cards[j] = new_cards[j];
        }
    }
    for(int i=1;i<55;++i){
        printf("%s",cards[i].c_str());
        if(i<54) printf(" ");
    }
    return 0;
}
相關文章
相關標籤/搜索