How many different numbers
Time Limit:1s Memory limit:32M
Accepted Submit:70 Total Submit:490

 

Recently oaiei has encountered a problem. And he needs your help.There are N numbers in an array and Q queries. For each query, there are two integers S and T. And the proplem is that there are how many different numbers in the index range [S,T] of the array (the array ‘s index is started from 1).

Input

 

There are multiple test cases. For each test case, the first line is an integer N (1<=N<=100000), indicating there are N numbers in the array. In the second line,there are N integers which are separated by a space. The third line is an integer Q(1<=Q<=1000), indicating there are Q queries. The following Q lines, for each line, there are two integers S and T(1<=S<=T<=N), indicating the index range of the array. The element value of the array will fit in a signed 32-bit integer.

 

Output

 

For each test, output an integer, indicating the number of different numbers in the index range [S,T] of the array.

 

Sample Input

10
1 2 3 3 3 3 4 -9 -9 10
2
1 5
5 10

Sample output

3
4 

Original: FOJ月赛-2008年10月

 

解题:

       用一般解法将会超时。用结构体存储给定的数字和下标。然后对结构体数组进行排序,排序后回归原下标序列。

#include <iostream> #include <stdlib.h> using namespace std; #define MaxSize 100002 struct numbers { int values; //值 int index; //下标 }aNumber[MaxSize]; int cmp(const void *a ,const void *b) { return (*(numbers*)a).values<(*(numbers*)b).values ? 1:-1; } int main() { int n,q,s,t,i,sum,count; bool used[MaxSize]; //判断相同的值是否已经加过了 int flags[MaxSize]; //存储排序后每个元素与前面不同的个数 memset(used,0,sizeof(used)); while (scanf("%d",&n)!=EOF) { count=0; sum=1; memset(flags,0,sizeof(flags)); for (i=0;i<n;i++) { scanf("%d",&aNumber[i].values); aNumber[i].index=i; } qsort(aNumber,n,sizeof(aNumber[0]),cmp); flags[aNumber[0].index]=sum; for (i=1;i<n;i++) { if (aNumber[i].values!=aNumber[i-1].values) { sum++; } flags[aNumber[i].index]=sum; } scanf("%d",&q); while (q--) { scanf("%d%d",&s,&t); for (i=s-1;i<t;i++) { if (used[flags[i]]==0) { count++; used[flags[i]]=1; } } printf("%d/n",count); memset(used,0,n); count=0; } } return 0; }