活动选择问题——贪心算法与动态规划

最优子结构

​ c[i][j] = c[i][k] + 1 + c[k][j]

​ c[i][j] = max( c[i][k] + 1 + c[k][j] ) (Sij 不空) (k = i+1….j-1 且k和前后前后活动兼容)

​ = 0 (Sij 空)

``````/*测试数据
注意Sij表示的意义是活动i结束后，活动j结束前的兼容活动，所以是双开区间
int s[] = { 0,1,3,0,5,3,5,6,8,8,2,12,_CRT_INT_MAX };
int f[] = { 0,4,5,6,7,9,9,10,11,12,14,16,_CRT_INT_MAX };
*/
#define N 11
void dp_act(int s[], int f[])
{
int i = 0;
int c[N + 2][N + 2] = { 0 };
for (int len = 2; len <= N+1; len++) {

for (i = 0; i <= N -len+1; i++) {
int j = i + len;
//Sij不为空
if (f[i] <= s[j]) {
int maxn = -1;
for (int k = i+1 ; k <j; k++) {
if (s[k] >= f[i] && f[k] <= s[j]) {
maxn = c[i][k] + c[k][j] + 1;
if (maxn > c[i][j]) {
c[i][j] = maxn;
}
}
}

}
}
}
}``````

``````int ret[10];
int ans = 0;
void recur_act_select(int s[], int f[], int k, int n)
{
int m = k + 1;  //m是每次第一个结束的活动的下标
while (m <= n && s[m] < f[k]) {
m++;
}
if (m <= n) {
ret[ans++] = m;
return recur_act_select(s, f, m, n);
}
return;
}``````

``````//尾递归改成循环
void gred_act_select(int s[], int f[], int n)
{
int k = 0;
int m = 0;
int ret[10] = { 0 };
int ans = 0;
while (k <= n) {
if (s[k] >= f[m]) {
ret[ans++] = k;
m = k;
}
k++;
}
}``````