1 条题解

  • 0
    @ 2025-5-8 15:01:12

    解题思路

    1. 初始化和输入处理
      • 定义二维数组 dp 用于存储中间结果,数组 aa 用于存储输入的数值,变量 n 表示数组大小,ab 是两个限制值。
      • 读取测试用例数量 nc
      • 对于每个测试用例:
        • 读取数组大小 n 和限制值 ab
        • 读取数组 aa 的元素,并对数组进行排序。
        • 初始化 dp 数组,将所有元素的值设为 -100000
    2. 深度优先搜索函数 dfs
      • 函数 dfs 接受两个参数 p(当前元素的索引)和 person(表示当前是哪个人在选择元素,01 分别表示不同的人)。
      • 如果 p 等于 n,表示已经遍历完数组,返回 0
      • 如果 dp[p][person] 大于 -100000,说明该状态已经计算过,直接返回 dp[p][person]
      • 初始化得分 score 为当前元素的值 aa[p],结果 res-100000
      • 找到第一个大于 score + a 的元素索引 i
      • 如果 i 等于 n,说明没有满足条件的元素,返回 dp[p][person] = score
      • 遍历 in 的元素,调用 dfs(i, 1 - person) 并更新 res
      • 返回 dp[p][person] = score - res
    3. 主函数 main
      • 初始化 i0,找到第一个大于 a 的元素索引 i
      • 初始化 res-100000,遍历 in 的元素,调用 dfs(i, 0) 并更新 res
      • 如果 res 等于 -100000,输出 0,否则输出 res
    #include<iostream>
    #include<algorithm>
    using namespace std;
    
    
    int dp[10001][2], aa[10001], n, a, b;
    
    int dfs(int p, int person){
    	if(p==n)
    		return 0;
    	
    	if(dp[p][person]>-100000)
    		return dp[p][person];
    	
    	int score = aa[p], res = -100000;
    	
    	int i = p+1;
    	while(i<n&&aa[i]<score+a)
    		i++;
    	if(i==n)
    		return dp[p][person] = score;
    	
    	while(i<n&&aa[i]<=score+b)
    		res = max(res,dfs(i,1-person)), i++;
    	
    	return dp[p][person] = score-res;
    }
    
    int main(){
    	int nc;
    	cin >> nc;
    	while(nc--){
    		cin >> n >> a >> b;
    		for(int i = 0; i < n; i++)
    			cin >> aa[i];
    		sort(aa,aa+n);
    		
    		for(int i = 0; i < n; i++)
    			dp[i][0] = dp[i][1] = -100000;
    		
    		int i = 0;
    		while(i<n&&aa[i]<a)
    			i++;
    		int res = -100000;
    		while(i<n&&aa[i]<=b)  
    			res = max(res,dfs(i,0)), i++;
    		if(res==-100000)
    			cout << 0 << endl;
    		else
    			cout << res << endl;
    	}
    }
    
    • 1

    信息

    ID
    679
    时间
    1000ms
    内存
    256MiB
    难度
    10
    标签
    递交数
    4
    已通过
    2
    上传者