這次的題目是 UVa 409 : Excuses, Excuses!
原文網址 :
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=6&page=show_problem&problem=350
題目翻譯請按此
解題想法 :
這題雖然簡單,但是實作起來有些複雜,一開始必須把所有的 excuse 的單字分開,然後存起來,最後在對所有的 keyword 做比較,計算最大值
在我的程式碼裡,我分別用 Keyword 和 Excuses 的 vector 儲存讀取進來的關鍵字和藉口 ( 藉口必須使用 getline ( ) 才能讀取 )
接著再用迴圈將所有的藉口裡的單字分開,在這裡我用了一個布林值 isNewWord ,因為有可能出現連續的符號,為了避免一碰到非英文的字元就將單字存入 vector 裡,才使用了 isNewWord 這個變數
還有一點要注意的是 : 關鍵字如果有出現在藉口裡的話,是不分大小寫的,所以我在分開單字的同時,也同時將所有英文字轉成小寫,這樣在比對的時候就可以很快地比對完成了
最後就是統計關鍵字出現的次數了,最後面計算次數的部分有一點複雜,我自己寫的時候也差一點搞混呢!
#include <iostream>
#include <stdio.h>
#include <vector>
#include <string.h>
#include <ctype.h>
using namespace std;
int main()
{
int K,E;
int Set = 1;
while (cin >> K >> E)
{
vector<string> Keyword;
vector<string> Excuses;
vector<string> Words[21];
vector<int> ExcusesNum;
int MaxExcuessNum = 0;
for (int i=0;i<K;i++)
{
string temp;
cin >> temp;
Keyword.push_back(temp);
}
char ch = getchar();
for (int i=0;i<E;i++)
{
string excuse;
getline(cin,excuse);
Excuses.push_back(excuse);
}
/*
把 excuse 中所有的單字拆開
並全部換成小寫
*/
for (int i=0;i<E;i++)
{
string word;
bool isNewWord = 1;
for (int j=0;j<Excuses[i].length();j++)
{
if ( isalpha(Excuses[i][j]) )
{
if ( !isNewWord )
word = "" , isNewWord = 1;
word.push_back(tolower(Excuses[i][j]));
}
else if ( isNewWord )
{
isNewWord = false;
Words[i].push_back(word);
}
}
}
/*
計算每一個 excuse 的 keyword 數量
並加到 vector 中儲存,同時計算出現最多的次數
*/
for (int i=0;i<E;i++)
{
int Num = 0;
for (int j=0;j<K;j++)
{
for (int k=0;k<Words[i].size();k++)
{
if ( Keyword[j] == Words[i][k] )
Num++;
}
}
MaxExcuessNum = max( MaxExcuessNum , Num );
ExcusesNum.push_back(Num);
}
cout << "Excuse Set #" << Set << endl;
for (int i=0;i<ExcusesNum.size();i++)
{
if ( ExcusesNum[i] == MaxExcuessNum )
cout << Excuses[i] << endl;
}
cout << endl;
Set++;
}
return 0;
}
後記 :
其實我當時在寫的時候寫了快一個小時 @@ ,覺得有一點慚愧啊!
不過還好一次就過了~~
沒有留言:
張貼留言