1. 程式人生 > 其它 >Atcoder ABC235 C

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;
		}
	}
}