Python 基本算法类型基础实战【LIS】

  • 最长上升子序列【LIS】

实话说Python解决这种问题,确实不如C++,在编码量上,估计手速签到题和大数计算Python占优势。

  • Python:
dp = [0]*30
a = [0, 389, 207, 155, 300, 299, 170, 158, 65]
len = 1
n = 8
dp[1] = a[1]
def lower_bound(l, r, x):
    ans = l
    while(l <= r):
        mid = int((l + r) / 2) #注意Python下标需要使用强制类型转化
        #print(mid)
        if a[i] >= dp[mid]:
            l = mid + 1;ans = mid
        else:
            r = mid - 1
    return ans

#print(a[1])
#for i in range(1, 9):
#    print(dp[i],end = ' ')
for i in range(2, 9):
    if a[i] >= dp[len]:
        len += 1
        dp[len] = a[i]
    else:
        p = lower_bound(1, len, i)
        #print(p)
        dp[p] = a[i]
print(len)
  • C++:
#include
#include
using namespace std;
const int maxn = 1e5 + 10;
int dp[maxn];
int a[maxn];
int n;
int main() {
	cin >> n;
	for (int i = 1; i <= n; i++) {
		cin >> a[i];
	}
	memset(dp, 0, sizeof dp);
	int len = 1;
	dp[1] = a[1];
	for (int i = 2; i <= n; i++) {
		if (a[i] >= dp[len]) {
			dp[++len] = a[i];
			continue;
		}
		int p = lower_bound(dp + 1, dp + len, a[i]) - dp;//如果查找未果,返回begin
		//cout << p << endl;
		dp[p] = min(a[i], dp[p]);

	}
	cout << len << endl;
	return 0;
}
//8 389 207 155 300 299 170 158 65

你可能感兴趣的:(Programming,Language,LIS,Python,ACM,OI)