CF101532G Magical Indices(暴力模拟)

题面:

Alaa sometimes feels bored at work, so at such times she starts playing with a beautiful array a consisting of n integers a1, a2, ..., an.

Alaa starts counting the number of magical indices in the array a. An index x is said to be magical if it satisfying the following rules:

  1. 1 < x < n
  2. ay ≤ ax, for each y (1 ≤ y < x).
  3. ax ≤ az, for each z (x < z ≤ n).

Can you help Alaa by counting the number of magical indices in the array a.

 

Input:

The first line contains an integer T, where T is the number of test cases.

The first line of each test case contains an integer n (1 ≤ n ≤ 106), where n is the size of the array a.

The second line of each test case contains n integers a1, a2, ..., an (1 ≤ ai ≤ 106), giving the array a.

 

Output:

For each test case, print a single line containing the number of magical indices in the array a.

 

Example:

CF101532G Magical Indices(暴力模拟)_第1张图片

 

Note:

As input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

 

分析:

嘛,就是求数a,它前面的数都比它小,后面的数都比它大,求存在多少个这样的数a。题目中的大小比较不需要严格按照顺序,所以想到了用bef数组存下从开头到当前位置为止最大的数,aft数组存下从末尾到当前位置为止最小的数,然后遍历一次,记录下大于等于bef[i],小于等于aft[i]的数有多少个就行了。WA了一发竟然是因为没看见是都是要算入等于的情况的,只算了严格大于小于。

 

AC代码:

#include
#include
using namespace std;
const int maxn = 1000010;
int t, n;
int num[maxn], bef[maxn], aft[maxn];

int main(){
	cin>>t;
	while(t--){
		cin>>n;
		for(int i = 1; i <= n; i++) scanf("%d", &num[i]);
		bef[1] = num[1];
		aft[n] = num[n];		
		for(int i = 2; i <= n; i++){
			if(num[i] > bef[i-1]) bef[i] = num[i];
			else bef[i] = bef[i-1];
		}
		for(int i = n - 1; i != 0; i--){
			if(num[i] < aft[i+1]) aft[i] = num[i];
			else aft[i] = aft[i+1];
		}
		int ans = 0;
		for(int i = 2; i < n; i++){
			if(num[i] >= bef[i-1]){
				if(num[i] <= aft[i+1]) ans++;
			}
		}
		cout<

 

你可能感兴趣的:(训练)