算法竞赛入门经典(第二版) | 例题5-1 大理石在哪 (普适查找)(UVa10474,Where is the Marble?)
大意:
給一序列,要求先將序列排序。再給n個數字,找到每個數字在序列中的位置
儲備知識→algorithm頭文件函數詳解
題目(提交)網址→UVa-10474
百度翻譯→百度翻譯
沒使用過該網站的同學請猛戳這里→vJudge教程
思路
數組存入,sort排序,find或lower_bound查找。
分析:
最開始沒有注意到n是有上限的,于是開了一個vector(小聲嗶嗶,vector比數組慢了一倍有余),將vector換成數組就是最佳解法了,第一個代碼是用find進行查找的。
代碼1(find):
#include<iostream> #include<algorithm> #include<vector> using namespace std; int main() {int n, q;vector <int> v;int num = 1;while(cin>>n>>q && n) {while(n--) { int x; cin >> x; v.push_back(x); } sort(v.begin(), v.end());cout << "CASE# " << num << ":" << endl; while(q--) { int x; cin >> x; vector<int>::iterator it, it1;//查找三部曲 int size = v.size();it = find(v.begin(), v.end(), x); //查找,如果沒找到,返回end() ,一般都是0 it1 = v.begin();//如果此處是(*it)>0,則會漏掉0,所以判斷是否查找成功的條件有兩個:it!=end()且*it == x; (((it-it1)!=size) && (*it) == x) ? cout << x << " found at " << (it-it1+1) << endl : cout << x << " not found" << endl;}num++;v.clear();}return 0;}下一個代碼是用lower_bound查找的。
代碼2(lower_bound)
#include<bits/stdc++.h> using namespace std; int n, m, a[100010], q, *p, num=0; int main() {while (cin >>n >>m && (n != 0 && m != 0)) {for (int i = 0; i < n; i ++) cin >>a[i];sort(a, a+n); // 升序排列printf("CASE# %d:\n", ++num);while (m --) {cin >>q;p = lower_bound(a, a+n, q); // 找到>=q的第一個數if (p - a != n && *p == q) printf("%d found at %d\n", q, p-a+1); // 存在且為qelse printf("%d not found\n", q); }}return 0; }收獲:
1、algorithm查找的用法
2、lower_bound(a, a+n, q); // 找到>=q的第一個數
3、upper_bound(a, a+n, q); // 找到>q的第一個數
4、vector很慢。主要面向方便 。
5、最開始對題意理解有偏差,忘記嚴格按照:
做題步驟:
??1、理解題意
??2、輸入輸出格式(最大值限制),結束格式
??3、測試規則
??4、思路
??5、代碼實現
執行了 。 以為沒有給n的大小的限制。
總結:
雖然是個大水題,但還是讓筆者鞏固了find查找的知識,代碼中判斷查找兩個條件判斷缺一不可,且適用于所有類型(數組、字符串、容器)。 以后可以只用這一種。不需要費力記憶和區分memchr或string頭文件的查找了。
總結
以上是生活随笔為你收集整理的算法竞赛入门经典(第二版) | 例题5-1 大理石在哪 (普适查找)(UVa10474,Where is the Marble?)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 为什么你的引用字体颜色那么淡? CSDN
- 下一篇: Dev-Cpp 常用的快捷键(持续更新)