2018年3月9日 星期五

[C_ST113-易] 水平濾波器(C++)

[C_ST113-易] 水平濾波器

Time Limit: 2 seconds
問題描述 :
請讀入一行由 0~9 組成的字串(長度 £ 100 )以及一個奇數 N ( N ≤ 11 ),接著針對每個字串中的字元 D ,就該字元 D 的前 (N-1)/2 個與後 (N-1)/2 個字元中,取得最大值 M ,接著來將字元 D 替換為最大值的字元 M ,最後輸出替換後的結果。
輸入說明 :
輸入資料只有一行,包含由空白隔開的兩個資料,第一個資料是由 0~9 構成的字串 ( 長度 ≤ 100) ,第二個數字是一個奇數 N ( N ≤ 11 )。
輸出說明 :
輸出問題描述中每個字元替換後的結果。
範例 :

輸入範例輸出範例
210548022512582201235412 5255888885558888823555554
  1. #include <iostream>  
  2. #include <string>    
  3. #include <sstream>    
  4. #include <vector>    
  5. using namespace std;  
  6.   
  7. int main() {  
  8.     // [C_ST113-易] 水平濾波器  
  9.     string str;  
  10.     getline(cin, str);  
  11.     int count = 0;  
  12.     string data;  
  13.     int N;  
  14.     stringstream ss(str);    
  15.      string token;    
  16.      //字串切割    
  17.      while (getline(ss, token, ' '))    
  18.      {    
  19.           
  20.         if(count == 0)  
  21.         {  
  22.             data = token;  
  23.             count++;  
  24.         }  
  25.         else  
  26.         {  
  27.             N = stoi(token);  
  28.         }  
  29.      }    
  30.      vector<int> ans;  
  31.        
  32.      for(int i = 0;i < data.size();i++)  
  33.      {  
  34.         int Max = -1;  
  35.         for(int j = i-((N-1)/2);j <= i+((N-1)/2);j++)  
  36.         {  
  37.             if(j >= 0 && (int)data[j]-48 > Max)  
  38.             {  
  39.                 Max = (int)data[j]-48;  
  40.             }  
  41.         }  
  42.         ans.push_back(Max);  
  43.      }  
  44.        
  45.      for(int i = 0;i < ans.size();i++)  
  46.      {  
  47.         cout << ans[i];  
  48.      }  
  49.      cout << endl;  
  50.     return 0;  
  51. }  

沒有留言:

張貼留言