嗜血魂K

导航

1.1 Broken Necklace

是我遇到的比较复杂的模拟了0 0  

这道题先是自己写的糟糕版,交上去WA了,跟着数据改..最后改得面目全非....昨天找标程交的!今天稍微修改了一下..就过了T T

这题对我来说没考虑到的是以下两点:

1.在枚举每个端口,统计最大长度的时候,没有想到要是全是某个字母,那不是不停转圈.

(另:我在编写此功能函数时,如果判重也很无力,等等看看标程)

2.就算考虑上面那一点,遇到全是某个字母的情况,会重复统计,我在最后判断统计长度大于输入长度则输出输入的长度

 标程重要的部分:

1.定义更为完整的mod,而我是每次mod各种判断,麻烦.

2.统计函数很值得我借鉴,首先,用dir储存方向,要单独处理的只是初始位置,接着是判重,有点考逻辑吧 = =

 

/* 
* Return n mod m. The C % operator is not enough because
* its behavior is undefined on negative numbers.
*/
int
mod(int n, int m)
{
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)
{
char color;
int i, n;

color = 'w';

/* Start at p if going forward, bead before if going backward */
if(dir > 0)
i = p;
else
i = mod(p-1, len);

/* We use "n<len" to cut off loops that go around the whole necklace */
for(n=0; n<len; n++, i=mod(i+dir, len)) {
/* record which color we're going to collect */
if(color == 'w' && necklace[i] != 'w')
color = necklace[i];

/*
* If we've 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;
}



 

/*
ID:y7276571
LANG: C
TASK: beads
*/
#include<stdio.h>
#include<string.h>
#define MAXLEN 350
int n,left[MAXLEN] = {0}, right[MAXLEN] = {0};
char beads[MAXLEN];
int getpos(int pos)
{
if(pos < 0) pos = n+pos;
else if(pos >= n) pos -= n;
return pos;
}
int maxlen_left(int pos)
{
int ans = 1, stop = pos;
char c;
while(stop - pos <= n)
{
if(beads[getpos(--pos)] == 'w') ans++;
else {c = beads[getpos(pos)]; break;}
}
while(stop - pos <= n)
{
if(beads[getpos(--pos)] == 'w') { ans++; continue; }
else
{
if(beads[getpos(pos)] == c) ans++;
else return ans;
}
}
}
int maxlen_right(int pos)
{
int ans = 1, stop = pos;
char c;
while(pos - stop < n)
{
if(beads[getpos(pos++)] == 'w') ans++;
else {c = beads[getpos(pos-1)]; break;}
}
while(pos - stop < n)
{
if(beads[getpos(pos++)] == 'w') { ans++; continue; }
else
{
if(beads[getpos(pos-1)] == c) ans++;
else return ans;
}
}
}
int main(void)
{
freopen("beads.in", "r", stdin);
freopen("beads.out", "w", stdout);
int i, j = 0, maxlen = 0;
scanf("%d%s", &n, beads);
for(i = 0; i < n; i++)
{
left[i] = maxlen_left(i);
right[i] = maxlen_right(i);
}
for(i = 0; i < n && !j; i++) maxlen = maxlen < left[i]+right[i] ?left[i]+right[i] : maxlen;
if(maxlen > n) printf("%d\n", n);
else printf("%d\n", maxlen);
exit(0);
}



posted on 2011-10-29 17:37  嗜血魂K  阅读(261)  评论(0编辑  收藏  举报