跳到正文

题解

题解:SP32879 SORTOUT - Mahammad and strings

Summer528约 1 分钟
原文
文章信息与版本

文章信息

发布
2026年8月11日
收录
2026年11月14日
更新
2026年11月21日
篇幅
约 1 分钟
题目
SP32879

版本

  1. v1当前

题目大意

就是寻找有多少个给的字符串小于等于查询的字符串。

思路

我们一开始能想到循环嵌套的写法,但时间复杂度 O(n×q)O(n \times q) 大概率会超时。因此,我们可以用排序和二分的优化方法。

先在输入后从小到大排序,再在询问时用上二分查找 upper_bound即可。

代码

C++
#include<bits/stdc++.h>
using namespace std;
string a;
vector<string> s;
int main(){
    long long n,q;
    cin>>n>>q;
    for(int i=0;i<=n-1;i++){
        string st;
        cin>>st;
        s.push_back(st);
    }
    sort(s.begin(),s.end());
    while(q--){
        long long ans=0;
        cin>>a;
        ans=upper_bound(s.begin(),s.end(),a)-s.begin();
        cout<<ans<<"\n";
    }
    return 0;
}
原文