發表文章

目前顯示的是 6月, 2018的文章

b923 stack 堆疊的模板題

題目原文 題目說明 實作 stack 三種功能:1. 刪除堆頂元素 2. 輸出頂端元素  3. 丟數字進堆疊。 思路 利用 STL 裡的堆疊分別使用 pop、top、push 三種 function。 #include<iostream> #include<stack> using namespace std; int main() { stack<int> s; int n; cin >> n; while(n--) { int select; cin >> select; if(select == 1) s.pop(); if(select == 2) cout << s.top() << endl; if(select == 3) { int num; cin >> num; s.push(num); } } }

d194 Unique Snowflakes

題目原文 題目說明 第一行輸入幾筆資料,第二行輸入此資料共幾片(n) 雪花,接下來 n 行代表雪花編號。 輸出可裝出最多不同雪花的數目 (需連續)。 思路 假設共 5 片雪花,編號分別是 4 1 4 2 3 5,從第一個 4 開始取,接下來是 1 和 4,碰到 4 時因為與第一個 4 編號相同,所以記下此次最多取出相異雪花數目為 2;接下來從 1 開始取,依序是 4 2 3 5,記下此次最多可取出相異數目為 5 ,並且每次取出數目時都與 max 比大小,最後傳回最大值即可。 #include<iostream> using namespace std; int check(int[], int); int main() { int t, n; scanf("%d", &t); while(t--) { scanf("%d", &n); int arr[n]; for(int i = 0; i < n; i++) scanf("%d", &arr[i]); int ans; ans = check(arr, n); printf("%d\n", ans); } } int check(int arr[], int n) { int max = 0; int count = 0; int stop = -1; for(int i = 0; i < n; i++) { for(int j = stop + 1; j < i; j++) { if(arr[j] == arr[i]) { stop = j; // 利用 stop 記住 i = stop + 1; // 往下一個移動 if(count > max) max = count; count = 0; } } count++; } if(count > max) return count; else return max; }

10815 Andy’s First Dictionary

題目原文 題目說明 輸入一段文章,輸出每一單字,並按字典序排列。 思路 一個單字一個單字去讀,若遇到像 andy's 這種詞,須將其切割為 andy 和 s 兩個單字, 讀完丟入 set (會自動依字典序排列),再利用迭代器輸出即可。 #include<iostream> #include<cctype> #include<cstring> #include<sstream> #include<set> using namespace std; set<string> dict; int main() { string input; while(cin >> input) { for(int i = 0; i < input.length(); i++) { if(isalpha(input[i])) input[i] = tolower(input[i]); else input[i] = ' '; // 非字母轉成空白字元 (ex. andy's 變 andy s) } stringstream ss; // 拿來切割 (ex. andy s 變兩個字串) ss << input; string output; while(ss >> output) dict.insert(output); // 會自動由小到大排 } set<string>::iterator it; for(it = dict.begin(); it != dict.end(); it++) cout << *it << endl; return 0; }