As a doll master, Alice owns a wide range of dolls, and each of them has a number tip on it's back, the tip can be treated as a positive integer. (the number can be repeated). One day, Alice hears that her best friend Marisa's birthday is coming , so she decides to sent Marisa some dolls for present. Alice puts her dolls in a row and marks them from 1 to n. Each time Alice chooses an interval from i to j in the sequence ( include i and j ) , and then checks the number tips on dolls in the interval from right to left. If any number appears more than once , Alice will treat this interval as unsuitable. Otherwise, this interval will be treated as suitable.
This work is so boring and it will waste Alice a lot of time. So Alice asks you for help .
Input
There are multiple test cases. For each test case:
The first line contains an integer n ( 3≤ n ≤ 500,000) ,indicate the number of dolls which Alice owns.
The second line contains n positive integers , decribe the number tips on dolls. All of them are less than 2^31-1. The third line contains an interger m ( 1 ≤ m ≤ 50,000 ),indicate how many intervals Alice will query. Then followed by m lines, each line contains two integer u, v ( 1≤ u< v≤ n ),indicate the left endpoint and right endpoint of the interval. Process to the end of input.
Output
For each test case:
For each query, If this interval is suitable , print one line "OK". Otherwise, print one line ,the integer which appears more than once first.
Print an blank line after each case.
Sample Input
5 1 2 3 1 2 3 1 4 1 5 3 5 6 1 2 3 3 2 1 4 1 4 2 5 3 6 4 6
Sample Output
1 2 OK 3 3 3 OK
题目大意:给出n个数,在区间[x, y]内找出从右向左出现不止一次的数,输出最右端的数字;没有输出OK;
思路:区间查询,就该往线段树方向上想;那么当百每个数字的左端离他最近的数字就录下来,在区间【x, y】内寻找最大值,那么就是右端起最先重复出现的数字,但是必须要 满足最大的数maxnum>=x, 否则是属于没有重复数字的,输出ok;
代码如下:
#include<stdio.h> #include<string.h> #include<iostream> #include<map> #include<math.h> #include<algorithm> using namespace std; #define N 500005 int dpmax[N][19], a[N]; int main() { int i, j, n, m, x, y; while(scanf("%d", &n)!=EOF) { map<int, int>M; memset(a, 0, sizeof(a)); for(i=1; i<=n; i++) { scanf("%d", &a[i]); dpmax[i][0]=M[a[i]]; M[a[i]]=i; } int mm=(int)floor(log(1.0*n)/log(2.0)); //n==500000时, mm=18 for(j=1; j<=mm; j++) for(i=n; i>=1; i--) if((i+(1<<(j-1)))<=n) dpmax[i][j]=max(dpmax[i][j-1], dpmax[i+(1<<(j-1))][j-1]); scanf("%d", &m); for(i=1; i<=m; i++) { scanf("%d%d", &x, &y); int mid=(int)floor(log(y*1.0-x+1)/log(2.0)); int maxnum=max(dpmax[x][mid], dpmax[y-(1<<mid)+1][mid]); if(maxnum<x) printf("OK\n"); else printf("%d\n", a[maxnum]); } printf("\n"); } return 0; }