[HDU] [1257] Minimum Interception System

Problem Description

Loading...

Problem Analysis

Consider that to maximize the number of shells hitting missiles, the missiles hit by the shells should be decreasing
So we need to fire LIS times; this means we cannot adjust it to hit more

General n2 DP algorithm:
For each a[i], determine whether a[0i] can update it to dp[j]+1
That is, see whether a[i] can be appended after some number in a[0
i]
to reach a new maximum

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include<stdio.h>
int a[30200],dp[30200];
int main() {
	int n;
	while(scanf("%d",&n)!=EOF) {
		for(int i=0; i<n; i++) {
			dp[i]=1;
			scanf("%d",&a[i]);
		}
		int res=0;
		for(int i=1; i<n; i++)
			for(int j=0; j<i; j++)
				if(a[i]>a[j]&&dp[i]<dp[j]+1) {
					dp[i]=dp[j]+1;
					if(res<dp[i])
						res=dp[i];
				}
		printf("%d\n",res);
	}
	return 0;
}

nlogn binary search algorithm:

Build an array to store the possibilities of the selected sequence
Then, for each a[i], find a position in s where s[k]<a[i]<s[k+1]
Then replace s[k+1] with a[i]
That is, try to use a smaller value to replace one that gives the same subsequence length
This increases the possibility that later numbers are larger than earlier ones
If after searching s we still do not have a[i]<s[k+1]
then it means a[i] is larger than every current number in s[k]
In this case, obviously a[i] should be appended to the end of s

Because the numbers in s must be monotonically increasing
binary search can be used when finding the position to optimize time
The binary search can be implemented by writing your own function
or by calling lower_bound in C++

Custom function:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <stdio.h>
int inf=99999999;
int n,l;
int a[30200];
int s[30200];
int find(int m) {
	int la=0,lb=l;
	while(lb>=la) {
		int mid=(la+lb)>>1;
		if(s[mid]==m)
			return mid;
		else if(s[mid]>m)
			lb=mid-1;
		else
			la=mid+1;
	}
	return la;
}
int main() {
	while(scanf("%d",&n)!=EOF) {
		for(int i=1; i<=n; i++)
			scanf("%d",&a[i]);
		s[0]=-1;
		l=1;
		for(int i=1; i<=n; i++) {
			s[l]=inf;
			int t=find(a[i]);
			if(t==l)
				l++;
			s[t]=a[i];
		}
		printf("%d\n",l-1);
	}
	return 0;
}

Using the C++ function:

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <stdio.h>
#include <algorithm>
using namespace std;
int inf=99999999;
int a[30200],s[30200];
int main() {
	int n;
	while(scanf("%d", &n)!=EOF) {
		for(int i=1; i<=n; i++)
			scanf("%d",&a[i]),s[i]=inf;
		int l=1;
		for(int i=1; i<=n; i++) {
			int k=lower_bound(s+1,s+n+1,a[i])-s;
			if(k==l)
				l++;
			s[k]=a[i];
		}
		printf("%d\n",l-1);
	}
	return 0;
}

Loading...