UVA 11078 Open Credit System(掃描 維護最大值)

賈樹丙發表於2013-07-20

Open Credit System

In an open credit system, the students can choose any course they like, but there is a problem. Some of the students are more senior than other students. The professor of such a course has found quite a number of such students who came from senior classes (as if they came to attend the pre requisite course after passing an advanced course). But he wants to do justice to the new students. So, he is going to take a placement test (basically an IQ test) to assess the level of difference among the students. He wants to know the maximum amount of score that a senior student gets more than any junior student. For example, if a senior student gets 80 and a junior student gets 70, then this amount is 10. Be careful that we don't want the absolute value. Help the professor to figure out a solution.

Input
Input consists of a number of test cases T (less than 20). Each case starts with an integer n which is the number of students in the course. This value can be as large as 100,000 and as low as 2. Next n lines contain n integers where the i'th integer is the score of the i'th student. All these integers have absolute values less than 150000. If i < j, then i'th student is senior to the j'th student.

Output
For each test case, output the desired number in a new line. Follow the format shown in sample input-output section.

Sample Input

3
2
100
20
4
4
3
2
1
4
1
2
3
4

Output for Sample Input

80
3
-1

題目大意:開放式學分制。給定一個長度為n的整數序列A0,A1,...,An-1,找出兩個整數Ai和Aj(i<j),使得Ai-A儘量大。

分析:使用二重迴圈會超時。對於每個固定的j,我們應該選擇的是小於j且Ai最大的i,而和Aj的具體數值無關。這樣,我們從小到大列舉j,順便維護Ai的最大值即可。

程式碼如下:

 

 1 #include<cstdio>
 2 #include<algorithm>
 3 using namespace std;
 4 int A[100000], n;
 5 int main() {
 6   int T;
 7   scanf("%d", &T);
 8   while(T--) {
 9     scanf("%d", &n);
10     for(int i = 0; i < n; i++) scanf("%d", &A[i]);
11     int ans = A[0]-A[1];
12     int MaxAi = A[0]; // MaxAi動態維護A[0],A[1],…,A[j-1]的最大值
13     for(int j = 1; j < n; j++) { // j從1而不是0開始列舉,因為j=0時,不存在i
14       ans = max(ans, MaxAi-A[j]);
15       MaxAi = max(A[j], MaxAi); //MaxAi晚於ans更新。想一想,為什麼
16     }
17     printf("%d\n", ans);
18   }
19   return 0;
20 }

 

 

 

相關文章