Gunner II--hdu5233(map&vector/二分)

时间:2022-02-14 20:03:29

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5233

题意:有n颗树,第 i 棵树的高度为 h[i],树上有鸟,现在这个人要打m次枪,每次打的高度是 q[i], 求每次

打枪能打下鸟的编号,否则输出-1 ;

STL中的map和vector:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <map> using namespace std; #define met(a, b) memset(a, b, sizeof(a))
#define INF 0x3f3f3f3f
#define N 100010 int dir[][] = { {,}, {-,}, {,}, {,-}, {,}, {,-}, {-,}, {-,-} }; int n, m, h[N], q[N]; map<int, vector<int> > mp; int main()
{
while(scanf("%d %d", &n, &m) != EOF)
{
mp.clear(); for(int i=; i<=n; i++) scanf("%d", &h[i]); for(int i=n; i>=; i--) mp[h[i]].push_back(i); for(int i=; i<=m; i++)
{
scanf("%d", &q[i]); if(mp[q[i]].size()>=)
{
printf("%d\n", mp[q[i]].back()); mp[q[i]].pop_back();
}
else printf("-1\n");
}
}
return ;
}

二分:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <map> using namespace std; #define met(a, b) memset(a, b, sizeof(a))
#define INF 0x3f3f3f3f
#define N 100010 int dir[][] = { {,}, {-,}, {,}, {,-}, {,}, {,-}, {-,}, {-,-} }; struct node
{
int num, Id;
}h[N]; int n, m, q[N], vis[N]; int cmp(node a, node b)
{
if(a.num!=b.num)
return a.num < b.num;
return a.Id < b.Id;
} int BeSearch(int L, int R, int num)
{
int ans = -; while(L <= R)
{
int Mid = (L+R)/; if(num == h[Mid].num)
{
if(!vis[Mid])
{
ans = Mid; R = Mid - ;///先输出最左边的;
}
else
L = Mid + ;
}
else if(h[Mid].num > num) R = Mid - ;
else L = Mid + ;
}
if(ans != -)
{
vis[ans] = ;
return h[ans].Id;
}
return -;
} int main()
{
while(scanf("%d %d", &n, &m) != EOF)
{
met(vis, );
met(h, );
met(q, ); for(int i=; i<n; i++)
{
scanf("%d", &h[i].num); h[i].Id = i+;
} sort(h, h+n, cmp); for(int i=; i<=m; i++)
{
scanf("%d", &q[i]); int pos = BeSearch(, n, q[i]); printf("%d\n", pos);
}
}
return ;
}