2017年12月30日 星期六

[C_AR183-易] 數字跑馬燈(C++)

[C_AR183-易] 數字跑馬燈

Time Limit: 2 seconds
問題描述 :
請讀入二行資料,第一行是一串空白隔開的數字(個數 N<=20 ),假設這是要顯示的跑馬燈,第二行是一連串讓跑馬燈資訊左右轉動的命令,可以指定這一串數字向左或者向右轉的次數,當一個數字從第一個位置向左轉出時,會移動到最後一個數字,反之亦然,一個數字從最後一個位置向右轉出時,會移動到第一個數字。下面例子說明跑馬燈轉動的過程:假設讀入的一串數字如下:
20 -5 -18 6 18 22 5 7 12 51 19
讀入的轉動命令為 L 5 R 13 R 2 L 7 , 表示向左移動, 表示向右移動,所以 L 5 表示向左移動 5 個位置, R 13 表示在向右移動 13 個位置等,則這些命令依序轉動的過程如下:
L 5 → 22 5 7 12 51 19 20 -5 -18 6 18
R 13 → 6 18 22 5 7 12 51 19 20 -5 -18
R 2 → -5 -18 6 18 22 5 7 12 51 19 20
L 7 → 12 51 19 20 -5 -18 6 18 22 5 7
最後一行即是全部轉動完畢之後,要輸出的結果。
輸入說明 :
輸入資料有兩行,第一行是由空白隔開的一串數字(最多 20 個),第二行是一串左轉或右轉的命令,命令之間由空白字元隔開,每個命令包含一個 L 或 R 字元(皆為大寫字元),接著一個整數 S ( S >= 0 ),表示往左或者往右轉動 S 個位置。 最多25個命令。
輸出說明 :
輸出該串數字經過這一連串的轉動命令之後的結果。
範例 :

輸入範例輸出範例
20 -5 -18 6 18 22 5 7 12 51 19
L 5 R 13 R 2 L 7
12 51 19 20 -5 -18 6 18 22 5 7
  1. #include <iostream>  
  2. #include<string>  
  3. #include <sstream>  
  4.   
  5. using namespace std;  
  6.   
  7. int main() {  
  8.     // [C_AR183-易] 數字跑馬燈  
  9.     string str;  
  10.     getline(cin, str);  
  11.     int tok[40];  
  12.     int count = 0;  
  13.     stringstream ss(str);  
  14.     string token;  
  15.     //字串切割  
  16.     while (getline(ss, token, ' '))  
  17.     {  
  18.         tok[count] = stoi(token);  
  19.         count++;  
  20.     }  
  21.     string dir;//方向  
  22.     getline(cin, dir);  
  23.     stringstream ssd(dir);  
  24.     string tokdir[50];  
  25.     int c = 0;  
  26.     //字串切割  
  27.     while (getline(ssd, token, ' '))  
  28.     {  
  29.         tokdir[c] = token;  
  30.         c++;  
  31.     }  
  32.     for(int i = 0;i < c;i+=2)  
  33.     {  
  34.         if(tokdir[i] == "L")  
  35.         {  
  36.             for(int j = 0;j < (stoi(tokdir[i+1])%count);j++)  
  37.             {  
  38.                 tok[count+j] = tok[j];  
  39.             }  
  40.             for(int j = 0;j < count;j++)  
  41.             {  
  42.                 tok[j] = tok[j+(stoi(tokdir[i+1])%count)];  
  43.             }  
  44.         }  
  45.         else if(tokdir[i] == "R")  
  46.         {  
  47.             for(int j = count-1;j >=0;j--)  
  48.             {  
  49.                 tok[j+(stoi(tokdir[i+1])%count)] = tok[j];  
  50.             }  
  51.             for(int j = 0;j < (stoi(tokdir[i+1])%count);j++)  
  52.             {  
  53.                 tok[j] = tok[count+j];  
  54.             }  
  55.         }  
  56.     }  
  57.     for(int i = 0;i < count;i++)  
  58.     {  
  59.         if(i != count-1)  
  60.             cout << tok[i] << " ";  
  61.         else  
  62.             cout << tok[i] << endl;  
  63.     }  
  64.     return 0;  
  65. }  

沒有留言:

張貼留言