ADS Homework 7-1 Favorite Color Stripe

这道题实际上是一个LCS问题的变种,首先去掉不喜欢的颜色,然后利用一个二维矩阵来进行迭代(消耗大量内存)。

#include <iostream>
#include <vector>

using namespace std;

vector<int> list[201];
int color_fav[201];
int old[10001];
int result[201][10000];

int FindColor(int color, int column){
	vector<int>& vec = list[color];
	for (int i = 0; i < vec.size(); i++)
		if (vec[i] <= column)
			return vec[i];
	return -1;
}
int main(){
	int colorNum, n;
	int i, j;
	cin >> colorNum >> n;
	for (i = 0; i < n; i++)
		cin >> color_fav[i];
	for (i = n - 1; i >= 0; i--)
		list[color_fav[i]].push_back(i);
	int length;
	cin >> length;
	for (i = 1; i <= length; i++)
		cin >> old[i];

	for (j = 0; j < n; j++)
		result[j][0] = 0;
	for (int temp = 0; temp < length; temp++){
		j = temp + 1;
		int color = old[j];
		for (i = 0; i < n; i++){
			if (FindColor(color, i) == -1)
				result[i][j] = result[i][j - 1];
			else{
				int index = FindColor(color, i);
				if (result[index][j - 1] + 1 > result[i][j - 1])
					result[i][j] = result[index][j - 1] + 1;
				else
					result[i][j] = result[i][j - 1];
			}
		}
	}
	cout << result[n - 1][length];
}

在网上看到过一个比较骚的是用一个一维数组来处理,原理很简单

//a and b are the two array, m and l are the length 
int getLongest(int *a, int *b, int m, int l) {
    int *d = new int[l];
    int len = 0;
    for (int i = 0; i < l; i++) {
        d[i] = 1; 
        for (int j = 0; j < i; j++) {
            if (order[b[j]] <= order[b[i]] && d[i] < d[j] + 1) {
                d[i] = d[j] + 1;
            }
        }
        if (len < d[i]) len = d[i];
    }
    return len;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值