發表文章

目前顯示的是有「UVa」標籤的文章

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; }

10474 Where is the Marble?

題目原文 題目說明 第一行輸入兩個數字 N 和 Q,分別代表:有 N 個大理石和查找 Q 個數。 接下來的 N 行代表大理石所寫上的數,由小到大依序排列,最後求題目所問某數在哪個位置。 思路 利用 algorithm 裡的 sort 進行排序,再利用 lower_bound 查找出位置。 lower_bound :用來找出第一個大於或等於某數的位置。 #include<cstdio> #include<algorithm> using namespace std; const int maxn = 10000; int main() { int n, q, arr[maxn], count = 0; while(scanf("%d %d", &n, &q) == 2 && n) { printf("CASE# %d:\n", ++count); for(int i = 0; i < n; i++) scanf("%d", &arr[i]); sort(arr, arr+n); while(q--) { int num; // 要搜尋的數 scanf("%d", &num); int pos = lower_bound(arr, arr+n, num) - arr; // 用 lower_bound 查找 num 的位置 if(arr[pos] == num) printf("%d found at %d\n", num, pos+1); else printf("%d not found\n", num); } } }

10004 Bicoloring

題目原文 題目說明 只有兩種顏色,且相鄰兩點需不同色,若可以達成,則輸出 BICOLORABLE,反之輸出 NOT BICOLORABLE。 思路 首先以 vector 建立表格來儲存與某節點相鄰的其他節點,以 queue 來儲存節點走訪的順序。 建立好連通表後,開始走訪,走訪做兩種事情:著色和檢查是否同色,可隨機從某點開始(以下程式碼以 n1 當第一個節點),將其 push 進 queue 裡並著上顏色,塗完顏色後以 current 記住後 pop 出去, 接著開始替相鄰節點(由連通表依序取出)著色,若相鄰節點尚未著色,則 push 到 queue 裡,當作下一個要走訪的 current,並著上與當前 current 相反顏色;已著色則檢查是否與當前 current 同色,同色則可確定非 bicolorable。著完後色都沒問題即為 bicolorable。 簡言之, 1. 建連通表  2. 按連通表依序著色  3. 著色過程中檢查是否符合規定。 #include<cstdio> #include<vector> #include<queue> int main() { int node; while(scanf("%d", &node) && node) { int edge, n1, n2; int color[200] = {0}; bool check = true; std::vector<int> vec[205]; // 所在列數代表它是第幾個點 後面push進和它連接的點 std::queue<int> que; scanf("%d", &edge); for(int i = 0; i < edge; i++) { scanf("%d %d", &n1, &n2); vec[n1].push_back(n2); // 建連通表 記得兩邊互相連接 vec[n2].push_back(n1); } que.push(n1); color[n1]...

10633 Rare Easy Problem

題目原文 題目說明 輸入 N - M 之值,輸出可能的 N 值。 思路 設 N = 10 * a + b,輸入 input = 10 * M + b - M = 9 * M + b 。以個位數處理,最後反求 N 值。 #include<stdio.h> int main(void) { long long input; int b; while(scanf("%lld",&input) && input) { int first = 0; for(b = 9; b >= 0; b--) // 逆向思考, 以個位數 b 處理 { if((input - b) % 9 == 0) // 若 input - b 再除以 9 為整數 (因為 M 為整數) { if(first) putchar(' '); first = 1; printf("%lld",(input - b) / 9 * 10 + b); } } printf("\n"); } }