Problem Description
Long long ago, there was a gunner whose name is Jack. He likes to go hunting very much. One day he go to the grove. There are n birds and n trees. The i-th bird stands on the top of the i-th tree. The trees stand in straight line from left to the right. Every tree has its height. Jack stands on the left side of the left most tree. When Jack shots a bullet in height H to the right, the nearest bird which stands in the tree with height H will falls.
Jack will shot many times, he wants to know which bird will fall during each shot.
Input
There are multiple test cases (about 5), every case gives n, m in the first line, n indicates there are n trees and n birds, m means Jack will shot m times.
In the second line, there are n numbers h[1],h[2],h[3],…,h[n] which describes the height of the trees.
In the third line, there are m numbers q[1],q[2],q[3],…,q[m] which describes the height of the Jack’s shots.
Please process to the end of file.
[Technical Specification]
All input items are integers.
1<=n,m<=100000(10^5)
1<=h[i],q[i]<=1000000000(10^9)
Output
For each q[i], output an integer in a single line indicates the id of bird Jack shots down. If Jack can’t shot any bird, just output -1.
The id starts from 1.
Sample Input
5 5
1 2 3 4 1
1 3 1 4 2
Sample Output
1
3
5
4
2
题目大意
题目有多组测试样例,每组测试样例,每个测试样例有3行,第一行有两个数n和m,n表示有n棵树,每棵数顶端有一只鸟,Jack会开m枪,第2行有n个数,表示1-n棵树的高度,第3行有m棵树,表示杰克开枪的高度,如果杰克开枪的高度上有鸟,那么那只鸟被打死,如果有多只,则打死最前面的,输出那只鸟所在的树为第几棵,如果没打到鸟,则输出-1
解题思路
建立map将int型和set型的数据联系起来键值为高度,而set则存储树为第几棵,set会对其数据进行排序,顶端为小值…
AC代码
#include <cstdio>
#include<map>
#include<set>
using namespace std;
int main()
{
map<int,set<int> >mm;
set<int>::iterator it;
int n,m;
while(~scanf("%d %d",&n,&m))
{
int i,j,x;
for(i=1;i<=n;++i)
{
scanf("%d",&x);
mm[x].insert(i);
}
for(j=0;j<m;++j)
{
scanf("%d",&x);
if(mm[x].empty())//如果为空表示没有鸟被打到
{
printf("-1\n");
}
else
{
it=mm[x].begin();//it指向set开始也就是最近的鸟
printf("%d\n",*it);
mm[x].erase(it);//鸟被打死就需要删了这个元素
}
}
}
}