PTA train scheduling (function use, upper_bound)

L2-014 Train dispatch (25 minutes)

analysis:

At the beginning, a loop was used to find the insertion position, the time was O(n*n), and the result was timeout, so the upper_bound (lower_bound) function was used instead, and the dichotomy was used to quickly search. In addition, by storing the minimum value of each track in ascending order, the code can also be simplified.

Code:

#include <bits/stdc++.h>
using namespace std;

int main()
{
    
    
	int n, ma[100010], ans = 0;
	cin >> n;
	while(n--){
    
    
	    int a;
		cin >> a;
		//从1开始储存,而非0,可以更加简化,但要注意下面的函数中地址也要从1开始
		if (a>ma[ans]) ma[++ans]=a;		
		else *upper_bound(ma+1,ma+ans+1,a)=a;
	}
	cout << ans;
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_43700916/article/details/88625043