c114: 00409 - Excuses, Excuses!

  1. 1. 內容
  2. 2. 範例輸入
  3. 3. 範例輸出
  4. 4. 想法
  5. 5. 程式碼

CPE 一顆星

題目連結:https://zerojudge.tw/ShowProblem?problemid=c114

內容

給定多個關鍵字以及若干字串,求出包含最多關鍵字的字串。

每筆測資第一列第一個數字 K (1 <= K <= 20) 代表關鍵字數量,第二個數字 E (1 <= E <= 20) 代表字串數量。接著為關鍵字和字串。

範例輸入

5 3
dog
ate
homework
canary
died
My dog ate my homework.
Can you believe my dog died after eating my canary… AND MY HOMEWORK?
This excuse is so good that it contain 0 keywords.
6 5
superhighway
crazy
thermonuclear
bedroom
war
building
I am having a superhighway built in my bedroom.
I am actually crazy.
1234567890…..,,,,,0987654321?????!!!!!!
There was a thermonuclear war!
I ate my dog, my canary, and my homework … note outdated keywords?

範例輸出

Excuse Set #1
Can you believe my dog died after eating my canary… AND MY HOMEWORK?

Excuse Set #2
I am having a superhighway built in my bedroom.
There was a thermonuclear war!

想法

先將字串中非英文字母的字元轉成空白,英文字母則轉成小寫,利用 stringstream 將字串內的單字一個一個抓出來跟關鍵字比對,並記錄次數,最後輸出最多關鍵字的字串即可。

程式碼

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(false), cin.tie(nullptr)
using namespace std;

int main(){
fastio;
int K, E, mxn, time[20], c = 0;
string key[20], s[20], temp, s1;
stringstream ss;
while(cin >> K >> E){
mxn = -50;
memset(time, 0, sizeof(time));
for(int i = 0; i < K; ++i) cin >> key[i] >> ws;
for(int i = 0; i < E; ++i){
getline(cin, s[i]);
s1 = s[i];
for(int j = 0; j < s1.length(); ++j){
if(isalpha(s1[j])){
if(isupper(s1[j])){
s1[j] = tolower(s1[j]);
}
}
else {
s1[j] = ' ';
}
}
ss << s1;
while(ss >> temp){
for(int j = 0; j < K; ++j){
if(temp == key[j]){
++time[i];
break;
}
}
}
mxn = max(time[i], mxn);
ss.str(""), ss.clear();
}
cout << "Excuse Set #" << ++c << "\n";
for(int i = 0; i < K; ++i){
if(time[i] == mxn){
cout << s[i] << "\n";
}
}
cout << "\n";
}
return 0;
}