https://vjudge.net/problem/UVA-11991
题意:
给出一个包含n个整数的数组,你需要回答若干询问。每次询问两个整数k和v,输出从左到右第k个v的下标。
思路:
把每个数字所出现的下标存储在vector中。
1 #include<iostream> 2 #include<string> 3 #include<cstring> 4 #include<algorithm> 5 #include<vector> 6 #include<map> 7 using namespace std; 8 9 const int maxn = 1000000 + 5; 10 11 int n, m; 12 vector<int> s[maxn]; 13 14 int main() 15 { 16 //freopen("D:\txt.txt", "r", stdin); 17 while (cin >> n >> m) 18 { 19 int x; 20 for (int i = 0; i < maxn; i++) 21 s[i].clear(); 22 for (int i = 1; i <= n; i++) 23 { 24 cin >> x; 25 s[x].push_back(i); 26 } 27 int k, v; 28 for (int i = 0; i < m; i++) 29 { 30 cin >> k >> v; 31 if (k <= s[v].size()) cout << s[v][k - 1] << endl; 32 else cout << '0' << endl; 33 } 34 } 35 }
刘汝佳的做法更妙一些。
#include<iostream> #include<string> #include<cstring> #include<algorithm> #include<vector> #include<map> using namespace std; int n, m; map <int, vector<int> > a; int main() { //freopen("D:\txt.txt", "r", stdin); while (cin >> n >> m) { a.clear(); int x; for (int i = 1; i <= n; i++) { cin >> x; if (!a.count(x)) a[x] = vector<int>(); a[x].push_back(i); } int k, v; for (int i = 0; i < m; i++) { cin >> k >> v; if (k <= a[v].size()) cout << a[v][k - 1] << endl; else cout << '0' << endl; } } }