王道机试指南3.2查找

例题3.4找x(哈尔滨工业大学上机题)

#include<iostream>
#include<cstdio>
using namespace std;
int main(){
    int n, x, flag = -1;
    cin >> n;
    int a[n];
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }
    cin >> x;
    for(int i = 0; i < n; i++){
        if(a[i] == x) flag = i;
    }
    cout << flag;
    return 0;
}

例题3.5查找(北京邮电大学上机题)

#include<iostream>
#include<cstdio>
using namespace std;
int main(){
    int n, m;
    cin >> n;
    int a[n];
    for(int i = 0; i < n; i++){
        cin >> a[i];
    }
    cin >> m;
    for(int i = 0; i < m; i++){
        int temp, flag = 0;
        cin >> temp;
        for(int j = 0; j < n; j++){
            if(a[j] == temp) flag = 1;
        }
        if(flag == 1) printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}  

习题3.5找最小数(北京邮电大学上机)

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node{
    int x, y;
}a[500];
bool cmp1(node a, node b){
    if(a.x != b.x) return a.x < b.x;
    else return a.y < b.y;
}
int main(){
    int n;
    cin >> n;
    for(int i = 0; i < n; i++){
        cin >> a[i].x >> a[i].y;
    }
    sort(a, a + n, cmp1);
    cout << a[0].x << " "<< a[0].y;
    return 0;
}  

习题3.6找位置(华中科技大学上机题)

#include<iostream>
#include<cstdio>
#include<string>
#include<string.h>
using namespace std;
int main(){
    string s;
    cin >> s;
    int flag[s.length()];//用于标记是否访问过 
    char c = '*';//用于记录是否是当前输出字符 
    int firstrow = 1;//标记第一个输出字符 
    memset(flag, 0, sizeof(flag));
    //从第一个字符开始遍历,如果后面出现与当前字符相同的字符则输出 
       for(int i = 0; i < s.length(); i++){
           if(flag[i] == 0){
            flag[i] = 1;
            int first = 1;
            //从当前字符的下一个字符开始寻找,相同字符 
            for(int j = i+1; j < s.length(); j++){
                if(s[i] == s[j]){
                    flag[j] = 1;
                    // 判断是否是第一行
                    if(s[i] != c && firstrow == 0) printf("\n");
                    //判断是否是第一个输出字符 
                    if(first == 1){
                        printf("%c:%d", s[i], i);
                    }
                    printf(",%c:%d", s[j], j);
                    first = 0;
                    c = s[i];
                    firstrow = 0;
                }
            }
        }    
    }
    return 0;
}