Atcoder ABC235 C
C - The Kth Time Query
题意
给定 n 个数,给定 t 个查询次数,每次查询给出值和这个值在n个数中是第几次出现的,如果存在,则输出值在数组中的位置,否则输出 -1。
题解
一道典型的用map映射的题,但是不是简单的对出现的string进行统计个数,还要记录位置,就用到了 map<string, vector<int>> m
小知识
map<string, vector<int>> m
输入:m["3"].push_back(3)
输出:m["3"][1]
代码
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
using namespace std;
int main(){
int n, t;
cin >> n >> t;
map<string, vector<int>> m;
for(int i = 0; i < n; i++){
string tmp;
cin >> tmp;
m[tmp].push_back(i + 1);
}
while(t--){
string x;
int k;
cin >> x >> k;
if(m[x].size() < k){
cout << "-1" << endl;
continue;
}
else{
cout << m[x][k - 1] << endl;
}
}
}

浙公网安备 33010602011771号