用一个 map 存放当前字符串是否出现过以及他的 ID,用一个计数器存放当前最高的 ID 排到了哪里。
读入一个字符串,当 map 中当前字符串所对应的下标未空则说明这个字符串是个新的字符串,计数器加一表示这个新字符串的 ID,将这个 ID 存到 map 中。反之则说明这个字符串已经被分配过 ID 了,直接输出之前 map 中存放的这个字符串对应的 ID 即可。
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
int q, c;
map<string, int> mp;
signed main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin >> q;
while (q--) {
string s; cin >> s;
auto it = mp.find(s);
if (it == mp.end()) mp[s] = ++c;
cout << mp[s] << "\n";
}
return 0;
}