[每日一題]AcWing 1442. 單詞處理器
阿新 • • 發佈:2022-03-20
輸入樣例:
10 7
hello my name is Bessie and this is my essay
輸出樣例:
hello my
name is
Bessie
and this
is my
essay
樣例解釋
第一行包含 7 個非空格字元,包括 “hello” 以及 “my”。
再加入 “name” 會使得第一行包含 11>7個非空格字元,所以這個單詞會被放到下一行。
(雙指標模擬)
1 #include <iostream> 2 #include <cstring> 3 #include <algorithm> 4using namespace std; 5 6 const int N = 110; 7 string s[N]; 8 int sum[N]; 9 int main() 10 { 11 int n, m; 12 cin >> n >> m; 13 14 for(int i = 1; i <= n; i ++){ 15 cin >> s[i]; 16 sum[i] = sum[i-1] + s[i].size(); 17 } 18 19 for (int i = 1, j = 1; i <= n; ) 20 { 21 while(sum[j]-sum[i-1] <= m && j <= n){ 22 j ++; 23 } 24 for(int k = i; k < j; k ++){ 25 cout << s[k]; 26 if(k != j-1) cout << " "; 27 } 28 cout << endl; 29i = j; 30 } 31 return 0; 32 }