5 条题解

  • 3
    @ 2026-10-4 9:50:30

    不使用upper_bound函数

    #include <bits/stdc++.h>
    #define int long long
    using namespace std;
    const int INF = 0x3f3f3f3f;
    const int N = 1e5 + 10;
    int n , m , cnt , a [N];
    signed main()
    {
    		cin >> n >> m;
    		for (int i = 1; i <= n; i++) cin >> a [i];
    		while ( m-- )
    		{
    			cin >> cnt;
                int l = 1 , r = n , ans = 0;
                while (l <= r)
                {
                    int mid = l + r >> 1;
                    if (cnt >= a [mid])//要查找的值大于当前值
                    {
                        if (a [mid] == cnt)
                            ans = max (ans , mid);
                        l = mid + 1;
                    } 
                    else r = mid - 1;
                }
                if (!ans) cout << "-1\n";
                else cout << ans << "\n";
    		}
    		return 0;
    }
    
    

    使用upper_bound函数

    #include <bits/stdc++.h>
    #define int long long
    using namespace std;
    const int INF = 0x3f3f3f3f;
    const int N = 1e5 + 10;
    int n , m , cnt , a [N];
    signed main()
    {
    		cin >> n >> m;
    		for (int i = 1; i <= n; i++) cin >> a [i];
    		while ( m-- )
    		{
    			cin >> cnt;
                if (a [(upper_bound (a + 1 , a + n + 1 , cnt) - a) - 1] != cnt) cout << "-1\n";
    			else cout << (upper_bound (a + 1 , a + n + 1 , cnt) - a) - 1 << "\n" ;
    		}
    		return 0;
    }
    
    
    

    信息

    ID
    3099
    时间
    1000ms
    内存
    256MiB
    难度
    2
    标签
    递交数
    60
    已通过
    30
    上传者