原来这样就可以快速读入:
while(~scanf("%ld%ld\n",&n,&m)){
gets(c+1);
l=strlen(c+1);
a[1].x =0;
for(int i=1,j=1;i<=l;++i){
if(c[i]!=' ')a[j].x=a[j].x*10+c[i]-'0';
else a[++j].x=0;
}
1.对树的高度和打枪的高度分别排序,用数组离线(按打枪顺序)存储结果:
const int maxn=105000;
struct node
{
int High;
int Id;
} A[maxn],B[maxn];
int C[maxn];
int cmp(node x,node y)
{
if(x.High==y.High)
return x.Id<y.Id;
return x.High<y.High;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.cpp","r",stdin);
#endif // ONLINE_JUDGE
int n,m;
while(~scanf("%d%d",&n,&m))
{
memset(C,-1,sizeof(C));
for(int i=0; i<n; i++)
{
scanf("%d",&A[i].High);
A[i].Id=i+1;
}
sort(A,A+n,cmp);
for(int i=0; i<m; i++)
{
scanf("%d",&B[i].High);
B[i].Id=i;
}
sort(B,B+m,cmp);
int j=0;
for(int i=0; i<n; i++)
{
if(A[i].High>B[j].High) { C[B[j++].Id]=-1; i-=1;}
else if(A[i].High<B[j].High)
continue;
else
C[B[j++].Id]=A[i].Id;
if(j==m) break;
}
for(int i=0; i<m; i++)
printf("%d\n",C[i]);
}
return 0;
}
离线的做法:找出所有不同的高度(最多1e5),用Map找该高度的位置。
const int maxn=100005;
vector<int> G[maxn];
map<int ,int> Mp;
set<int> S[maxn];
int p[maxn];
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.cpp","r",stdin);
#endif // ONLINE_JUDGE
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<=n;i++)
S[i].clear();
Mp.clear();
int cur,a;
int cnt=0;
for(int i=1;i<=n;i++)
{
scanf("%d",&a);
if(!Mp.count(a)) Mp[a]=++cnt;
cur=Mp[a];
S[cur].insert(i);
}
while(m--)
{
int b;
scanf("%d",&b);
if(!Mp.count(b)) puts("-1");
else
{
cur=Mp[b];
if(!S[cur].size())
puts("-1");
else
{
printf("%d\n",*S[cur].begin());
S[cur].erase( S[cur].begin());
}
}
}
}
return 0;
}
3. 将上面的Set 改为Vector二维数组存储即可
vector<int>G[maxn];
int cnt,p[maxn];
map<int,int>mp;
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.cpp","r",stdin);
#endif // ONLINE_JUDGE
while(scanf("%d%d",&n,&m)!=EOF)
{
mp.clear();
for(int i=1;i<=n;i++)
G[i].clear();
cnt=0;
int cur;
for(int i=1;i<=n;i++)
{
scanf("%d",&h[i]);
if(!mp.count(h[i]))
{
mp[h[i]]=++cnt;
}
cur=mp[h[i]];
G[cur].push_back(i);
}
for(int i=0;i<=cnt;i++)
p[i]=0;
while(m--)
{
scanf("%d",&cur);
if(!mp.count(cur))
{
puts("-1");
continue;
}
cur=mp[cur];
if(p[cur]>=(int)G[cur].size())
{
puts("-1");
continue;
}
printf("%d\n",G[cur][p[cur]]);
p[cur]++;
}
}
return 0;
}