- 2
- 0
- 约9.01万字
- 约 11页
- 2016-12-03 发布于河南
- 举报
P1002:《破的项链》讲义
《破碎的项链》讲义
路中信息学
学习目标:
函数的调用
字符串读取,及构建循环串2*S
标准的搜索、模拟解题,比较直观:时间复杂度为O(N2)
借助递推思想,初步了解动态规划简单思想O(N)
程序调试技巧
(DP+mod):按这个动规的思路,还有另外一种变形,用模运算来处理环这样初值不能简单地用bl[0]=rl[0]=0来表示,我们没有任何理由认为0位置应当为初始位置(在用模运算处理环的情况下)应该在项链中找到第一个b,则此位置的rl,rr都为0,从这个位置按照上面的递归关系进行DP计算rl,rr,如果没有b,那么整个项链都可看做红色,直接输出n即可。同理,可以计算bl,br以及最后的结果,简洁的C代码已贴在代码页。
事实上不必使用动态规划,直接搜索亦可达到O(n)。把两个同样的项链放在一块,从头开始用两个变量(变量)a,b记录自左方某点至目前为止可搜集到之两种颜色珠子数,取途中所出现a+b之最大值,遇颜色变换时再将b指定给a即可,代码十分简洁。
思路二:
每次将串s的首位移动至末位,每次均能从两头开始搜索,无需考虑环的问题。
思路三:
无需考虑w的。进行分类讨论,只有rb和br两种情况。
但是如果是rrrrwbbbbrb呢??
/*******************************************************************************************/
思路1:这道题用标准的搜索是O(n^2)的/*******************************************************************************************/
#include stdio.h
#include string.h
#include assert.h//提供assert( )诊断表达式的真值,增强程序的健壮性
?
#define MAXN 400
?
char necklace[MAXN];
int len;
?
/*
* Return n mod m. The C % operator is not enough because
* its behavior is undefined on negative numbers.
*/
int
mod(int n, int m)//mod( )为项链珠子实现循环选择[0~~m-1]
{
while(n 0)
n += m;
return n%m;
}
?
/* * Calculate number of beads gotten by breaking
* before character p and going in direction dir,
* which is 1 for forward and -1 for backward.
*/
int
nbreak(int p, int dir)// 搜集珠子数量,从p位置出发;dir取值-1表示向左、1表示向右方向
{
char color;
int i, n;
?
color = w;//color是一个很好的染色珠子颜色标记,用来记录搜集过程中将遇到的珠子的颜色,并过滤’w’白色。
?
/* Start at p if going forward, bead before if going backward */
if(dir 0)
i = p;//右方向[p……
else
i = mod(p-1, len); //左方向[……p-1
?
/* We use nlen to cut off loops that go around the whole necklace */
for(n=0; nlen; n++, i=mod(i+dir, len)) {//判断完所有项链珠子,循环完成一周结束
/* record which color were going to collect */
if(color == w necklace[i]?!= w)//设置染色珠子颜色标记
color = necklace[i];
?
/*
* If weve chosen a color and see a bead
* not white and not that color, stop
*/
if(color?!= w necklace[i]?!= w necklace[i]?!= color)
break;
}
return n;
}
?
vo
原创力文档

文档评论(0)