这题还是从《算法入门经典》上附的。 归类居然是回溯!!
我就傻傻的按着回溯的思想,或者说第一印象,也就是第一个想到的就是排序后二分查找。
结果悲剧TLE
然后才想到可是在每次输入的时候就存到个数组里, 也就是hash思想吧。
#include <cstdio> #include <algorithm> #include <cstring> using namespace std; long hash[10005]; long ans, N, query; int main() { long curCase = 0; while(++ curCase) { memset(hash, 0, sizeof(hash)); long i, Q; scanf("%ld%ld", &N, &Q); if(N == 0 && Q == 0) { break; } printf("CASE# %ld:\n", curCase); long cur; for(i = 1; i <= N; i ++) { scanf("%ld", &cur); hash[cur] ++; } while(Q --) { scanf("%ld", &query); ans = 0; if(!hash[query]) { printf("%ld not found\n", query); } else { for(i = 0; i < query; i ++) { ans += hash[i]; } printf("%ld found at %ld\n", query, ans + 1); } } } return 0; }
再然后,看了别人代码
#include<stdio.h> #include<string.h> int main() { const long maxn=10008; long n,m,test=0,be[maxn],pos[maxn]; while(scanf("%ld%ld",&n,&m)==2) { if(n==0||m==0) break; test++; printf("CASE# %ld:\n",test); memset(be,0,sizeof(be)); memset(pos,0,sizeof(pos)); for(long i=1;i<=n;i++) { long t; scanf("%ld",&t); be[t]++; } long tmp=0; for(long i=0;i<maxn;i++) if(be[i]) { pos[i]=tmp+1; tmp+=be[i]; } for(long i=1;i<=m;i++) { long t; scanf("%ld",&t); if(pos[t]) printf("%ld found at %ld\n",t,pos[t]); else printf("%ld not found\n",t); } } return 0;
才突然意识到,可以打表啊!!
败