【问题描述】
You have n problems. You have estimated the difficulty of the i-th one as integer ci. Now you want to prepare a problemset for a contest, using some of the problems you've made.
A problemset for the contest must consist of at least two problems. You think that the total difficulty of the problems of the contest must be at least l and at most r. Also, you think that the difference between difficulties of the easiest and the hardest of the chosen problems must be at least x.
Find the number of ways to choose a problemset for the contest.
The first line contains four integers n, l, r, x (1 ≤ n ≤ 15, 1 ≤ l ≤ r ≤ 109, 1 ≤ x ≤ 106) — the number of problems you have, the minimum and maximum value of total difficulty of the problemset and the minimum difference in difficulty between the hardest problem in the pack and the easiest one, respectively.
The second line contains n integers c1, c2, ..., cn (1 ≤ ci ≤ 106) — the difficulty of each problem.
Print the number of ways to choose a suitable problemset for the contest.
3 5 6 1 1 2 3
2
4 40 50 10 10 20 30 25
2
5 25 35 10 10 10 20 10 20
6
In the first example two sets are suitable, one consisting of the second and third problem, another one consisting of all three problems.
In the second example, two sets of problems are suitable — the set of problems with difficulties 10 and 30 as well as the set of problems with difficulties 20 and 30.
In the third example any set consisting of one problem of difficulty 10 and one problem of difficulty 20 is suitable.
【解决思路】
这道题目主要考查的是深度优先搜索与回溯,从题库中选题满足题目要求的难度总和以及跨度。
(1)首先对深度优先搜索的起点进行遍历。
(2)每次循环中首先要记录上一步的难度总和sum、难度最小值min和难度最大值max,以便之后还原进行回溯。
(3)加入当前节点,更新sum、min和max(注意min不为0)。
(4)如果题目的条件(sum>= l && sum <= r && max - min >= x),则选题的方法数加一。
(5)如果当前节点不是最后一个节点,而且题目难度总和尚未超过题目要求的限度,则以下一个节点为起点进行深度优先搜索。
(6)最后还原sum、min和max,回溯访问下一个节点。
【代码实现】
#include <iostream>
#include <vector>
int c[15]; // value of difficulty
int n, l, r, x; // number of sets, minimun value of total difficulty,maximun value of total difficulty, minimun range of diffculty
int num = 0, sum = 0, min = 0, max = 0; //number of ways, sum of value of total difficulty, minimun value of difficulty, maximun value of difficuly
void dfs(int start)
{
for(int i = start; i < n; i++)
{
int this_sum = sum;
int this_min = min;
int this_max = max;
sum += c[i];
min = min < c[i] && min != 0 ? min : c[i]; // min != 0
max = max > c[i] ? max : c[i];
if(sum >= l && sum <= r && max - min >= x)
num++;
if(i < n - 1 && sum <= r)
dfs(i + 1);
//backtrack
sum = this_sum;
min = this_min;
max = this_max;
}
}
int main()
{
std::cin >> n >> l >> r >> x;
for(int i = 0; i < n; i++)
std::cin >> c[i];
dfs(0);
std::cout << num << std::endl;
}
本文介绍了一种使用深度优先搜索与回溯算法来解决比赛题集组合的问题。具体包括:输入参数为题库数量及题目的难度范围等,通过算法找出符合难度总和及跨度要求的所有组合方式。
588

被折叠的 条评论
为什么被折叠?



