Gunner II

时间:2022-07-28
本文章向大家介绍Gunner II,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

题意描述

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.

给定n棵树和猎人能够进行的m次射击,每次射击能够射下相应高度最近树的鸟,询问落下鸟的顺序。

思路

我们可以使用结构体数组来存储树的序号与树的高度,使用两个数组来存储相应的序号和高度,同样可以使用lower_bound来寻找与射击高度相同的树,如果找到,则让对应的下标数组加1,没有找到则置-1。

下面来举个例子,对于样例

5 5 1 2 3 4 1 1 3 1 4 2

排序过后如图:

而对应的low数组和h数组如下:

low[1]=[1],low[2]=5,low[3]=2,low[4]=3,low[5]=4 h[1]=1,h[2]=1,h[3]=2,h[4]=3,h[5]=4

如果寻找到第一颗高为1的树,则low[1]++成为2,当到第二个高为1的样例时,h[low[p]]=5,匹配成功。

AC代码

#include<bits/stdc++.h>
#define x first
#define y second
#define IOS ios::sync_with_stdio(false);cin.tie(0);
using namespace std;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
typedef pair<long,long> PLL;
typedef pair<char,char> PCC;
typedef long long LL;
const int N=1e5+10;
const int M=150;
const int INF=0x3f3f3f3f;
const int MOD=998244353;
struct node{
    int idx,h;
}Node[N];
bool cmp(node a,node b){
    if(a.h!=b.h) return a.h<b.h;
    return a.idx<b.idx;
}
int h[N],low[N];
void solve(){
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF){
        for(int i=1;i<=n;i++){
            scanf("%d",&Node[i].h);
            Node[i].idx=i;
        }
        sort(Node+1,Node+1+n,cmp);
        for(int i=1;i<=n;i++) low[i]=i,h[i]=Node[i].h;
        for(int i=1;i<=m;i++){
            int x;scanf("%d",&x);
            int p=lower_bound(h+1,h+1+n,x)-h;
            if(h[low[p]]!=x) printf("-1n");
            else{
                printf("%dn",Node[low[p]].idx);
                low[p]++;
            }
        }
    }
}
int main(){
    //IOS;
    solve();
    return 0;
}