PTA 1112 Exceeding the range of C++ to achieve ultra-detailed analysis

The picture above is a line chart drawn from the data collected in a scientific research, where the red horizontal line indicates the threshold of normal data (the threshold in this picture is 25). Your task is to find out the interval where the abnormal data exceeds the threshold. For example, 3 data points in the interval [3, 5] on the horizontal axis in the figure above exceed the standard, and the data point corresponding to point 9 on the horizontal axis (which can be expressed as the interval [9, 9]) also exceeds the standard.

Input format:

The first line of input gives two positive integers N (≤104) and T (≤100), which are the number of data points and the threshold, respectively. The second line gives the ordinates of N data points, all of which are positive integers not exceeding 1000, and the corresponding abscissas are integers from 0 to N−1.

Output format:

Output the intervals of excess data in order from left to right, each interval takes up one line, and the format is where  [A, B]and  A are  the left and B right endpoints of the interval. If no data exceeds the standard, output the maximum value of all data in one line.

Input sample 1:

11 25
21 15 25 28 35 27 20 24 18 32 23

Output sample 1:

[3, 5]
[9, 9]

Input sample 2:

11 40
21 15 25 28 35 27 20 24 18 32 23

Output sample 2:

35

Problem-solving ideas:

Traverse each number to determine the left and right intervals

Code example:

#include <bits/stdc++.h>

using namespace std;

int main() {
	int n, max_v; //数据点的数量和阈值
	cin >> n >> max_v;

	vector<int> nums; //存数值
	for (int i = 0; i < n; i++) {
		int num;
		cin >> num;
		nums.emplace_back(num);
	}

	int max_val = *max_element(nums.begin(), nums.end()); //先取得最大的数值

	int left = 0, right = 0; //左、右区间
	bool flag = true; //区间确定的标志
	bool has_best = false; //数值中是否有大于阈值的数的标志,若有则为true
	for (int i = 0; i < nums.size(); i++) {
		if (nums[i] > max_v) {
			has_best = true; //代表数值中有大于阈值的数的标志
			if (flag) {
				left = i;
				flag = false; //左区间确定的标志,同时也是右区间开始确定的标志
			}
			right = i; //确定右区间
		}
		else { //一旦有数小于等于阈值则代表区间已经确定完毕
			if (!flag) { //在确定右区间的过程中flag为false
				printf("[%d, %d]\n", left, right);
				flag = true; //初始化
			}
		}
	}
    //如果i已经走到了数值的最后且最后一个区间已确定
    //但由于i的自增而被迫退出循环,会导致未输出最后一个区间
    //因次下面这个if语句的存在是有必要的
	if (!flag) { 
        printf("[%d, %d]\n", left, right);
    }
    
    if (!has_best) { //代表数值中没有大于阈值的数,输出数值中的最大值
		cout << max_val << endl;
	}
    

	return 0;
}

operation result:

 

Guess you like

Origin blog.csdn.net/m0_53209892/article/details/129328281