跳到正文

科技·工程

[NBMT FirstRound]谐乐 题解

GuTianYi约 6 分钟
原文
文章信息与版本

文章信息

发布
2025年2月13日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 6 分钟

版本

  1. v2当前
  2. v1

难度:提高+/省选-

难度评选理由:根据《NOI大纲(2023年修订版)》解释,状态压缩动态规划为提高级(7级)难度,略高于提高。因此,将该题目评定为提高+/省选-。

本题AI各个测试得分:

测试#1:AC,100pts

os:我也特别震惊,AI的解法我也会在最底下分享。

这题使用dfs会超时。

观察一下数据范围,n很小。又是类似于取数字的问题。因此,我们可以使用状压dp。

对于每一种状态,寻找它是否满足单调上升或单调下降即可。

代码:

C++
#include<bits/stdc++.h>
using namespace std;
int n,a[1005],ans=0,pos=1;
bool check(int z){
	int l=z,k=n,last=1e7;
	while(l){
		//cout<<z<<" "<<l<<" "<<last<<endl;
		if(l&1){
			if(a[k]>=last){
				//cout<<k<<" "<<a[k]<<">="<<last<<endl;
				break;
			}
			else last=a[k];
		}
		--k;
		l>>=1;
	}
	if(l==0){
		return true;
	}
	else return false;
}
bool check2(int z){
	int l=z,k=n,last=-1e7;
	while(l){
		//cout<<z<<" "<<l<<" "<<last<<endl;
		if(l&1){
			if(a[k]<=last){
				//cout<<k<<" "<<a[k]<<"<="<<last<<endl;
				break;
			}
			else last=a[k];
		}
		--k;
		l>>=1;
	}
	if(l==0){
		return true;
	}
	else return false;
}
int main(){
	int T;
	cin>>T;
	while(T--){
		ans=1;
		cin>>n;
		for(int i=1;i<=n;i++) cin>>a[i];
		for(int i=1;i<(1<<n);i++){
			if(check(i)||check2(i)){
				int j=i,ccf=0;
				while(j){
					if(j&1) ++ccf;
					j>>=1;
				}
				ans=max(ans,ccf);
				pos=i;
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}

AI解法(AI生成):

本题要求找出一个序列中最长的单调递增子序列(LIS)或最长的单调递减子序列(LDS)的长度,并输出其中的较大值。为了解决这个问题,我们可以分别计算LIS和LDS的长度,然后比较两者得出结果。

最长递增子序列(LIS)的计算: 使用一个动态规划数组dp_inc,其中dp_inc[i]表示以序列中第i个元素结尾的最长递增子序列的长度。 遍历序列,对于每个元素,我们在它之前的元素中查找能够构成递增子序列的最大长度,并加1更新到dp_inc[i]中。

遍历结束后,dp_inc中的最大值即为LIS的长度。

最长递减子序列(LDS)的计算: 使用一个类似的动态规划数组dp_dec,其中dp_dec[i]表示以序列中第i个元素结尾的最长递减子序列的长度。 遍历序列,对于每个元素,我们在它之前的元素中查找能够构成递减子序列的最大长度,并加1更新到dp_dec[i]中。

遍历结束后,dp_dec中的最大值即为LDS的长度。

比较LIS和LDS的长度,输出较大的那个。

代码:

C++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int longestIncreasingSubsequence(const vector<int>& seq) {
    vector<int> lis;
    for (int num : seq) {
        auto it = lower_bound(lis.begin(), lis.end(), num);
        if (it == lis.end()) {
            lis.push_back(num);
        } else {
            *it = num;
        }
    }
    return lis.size();
}

int longestDecreasingSubsequence(const vector<int>& seq) {
    vector<int> lds;
    for (int num : seq) {
        auto it = upper_bound(lds.rbegin(), lds.rend(), num, greater<int>());
        if (it == lds.rend()) {
            lds.insert(lds.begin(), num);
        } else {
            *it = num;
        }
    }
    return lds.size();
}

int main() {
    int T;
    cin >> T;
    while (T--) {
        int n;
        cin >> n;
        vector<int> seq(n);
        for (int i = 0; i < n; ++i) {
            cin >> seq[i];
        }
        int lis_length = longestIncreasingSubsequence(seq);
        int lds_length = longestDecreasingSubsequence(seq);
        cout << max(lis_length, lds_length) << endl;
    }
    return 0;
}
原文