查询数字的位置——uva11911

查询某个数字第N次出现在数列的位置

map

View Code
#include<stdio.h>
#include<map>
#include<string.h>
#include<iostream>
using namespace std;

int mhash[1000099];

struct data{
    int x,y;
    friend bool operator <(data a,data b){//用map一定要写,不然会出错
        if(a.y==b.y)
        return a.x<b.x;
        else 
            return a.y<b.y;
    }
};

int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF){
        memset(mhash,0,sizeof(mhash));
        map<data,int>mm;
        
        int i,a,b;
        data temp;
        for(i=1;i<=n;i++){
            scanf("%d",&a);
            mhash[a]++;
            temp.x=mhash[a];
            temp.y=a;
            mm[temp]=i;
        }
        for(i=1;i<=m;i++){
            scanf("%d%d",&a,&b);
            temp.x=a;
            temp.y=b;
            if(mm.find(temp)==mm.end())
                printf("0\n");
            else
                printf("%d\n",mm[temp]);
        }
    }

    return 0;
}

别人的比较精简的代码

View Code
#include<cstdio>
#include<map>
#include<vector>
using namespace std;
map<int ,vector<int> > mm;
int main(){
    int n,m,a, k,v;
    while(scanf("%d%d",&n,&m)==2){
        mm.clear();
        for(int i=1;i<=n;i++){
            scanf("%d",&a);
            mm[a].push_back(i);
        }
        while(m--){
           scanf("%d%d",&k,&v);
           if(mm[v].size()<k) printf("0\n");
           else   printf("%d\n",mm[v][k-1]);
        }
    }
    return 0;

}
原文地址:https://www.cnblogs.com/huhuuu/p/2893470.html