P1918 保龄球

map

const int N=2e5+10;
unordered_map<int,int> mp;
int n,m;

int main()
{
    cin>>n;

    for(int i=1;i<=n;i++)
    {
        int x;
        cin>>x;
        mp[x]=i;
    }

    cin>>m;

    while(m--)
    {
        int x;
        cin>>x;
        if(mp.count(x)) cout<<mp[x]<<endl;
        else cout<<0<<endl;
    }
    //system("pause");
}

重载lower_bound

const int N=1e5+10;
struct Node
{
    int x;
    int id;
    bool operator<(const Node &W) const
    {
        return x<W.x;
    }
}a[N];
int n,m;

bool cmp(Node a,int b)
{
    return a.x<b;// 找到第一个>=b的结构体元素
}

int main()
{
    cin>>n;

    for(int i=1;i<=n;i++) cin>>a[i].x,a[i].id=i;
    sort(a+1,a+n+1);

    cin>>m;

    while(m--)
    {
        int x;
        cin>>x;
        int p=lower_bound(a+1,a+n+1,x,cmp)-a;
        if(p>n || a[p].x != x) cout<<0<<endl;
        else cout<<a[p].id<<endl;
    }
    //system("pause");
}
原文地址:https://www.cnblogs.com/fxh0707/p/13617047.html