会员
众包
新闻
博问
闪存
赞助商
HarmonyOS
Chat2DB
所有博客
当前博客
我的博客
我的园子
账号设置
会员中心
简洁模式
...
退出登录
注册
登录
SDJL的足迹
首页
博问
闪存
管理
USACO_1_1_Broken Necklace
/**/
/*
ID: sdjllyh1
PROG: beads
LANG: C++
complete date: 2008/9/8
efficiency: O(n^2)
author: LiuYongHui From GuiZhou University Of China
more article: www.cnblogs.com/sdjl
*/
#include
"
stdafx.h
"
#include
<
iostream
>
#include
<
fstream
>
#include
<
string
>
using
namespace
std;
//
打断的珠子类(直线形)
class
BROKEN_NECKLACE
{
private
:
string
m_beads;
//
珠子数据
int
m_len;
//
珠子长度
public
:
//
构造打断的珠子
BROKEN_NECKLACE(
const
string
&
beads)
{
m_beads
=
beads;
m_len
=
m_beads.length();
}
//
计算从两头可以拿到的珠子数
int
GetBeadsFromBothSides()
{
//
===============从前向后拿==================
int
retBeadsCount
=
1
;
int
fetchIndex
=
1
;
//
当前准备拿的珠子所在位置
char
color
=
m_beads[
0
];
//
应该拿的颜色
char
nextColor
=
m_beads[fetchIndex];
//
当前准备拿的颜色
while
((color
==
nextColor)
||
(nextColor
==
'
w
'
)
||
(color
==
'
w
'
))
{
if
((color
==
'
w
'
)
&&
(nextColor
!=
'
w
'
))
color
=
nextColor;
retBeadsCount
++
;
m_beads[fetchIndex]
=
'
n
'
;
//
n 表示 no bead
fetchIndex
++
;
if
(fetchIndex
<
m_len)
{
nextColor
=
m_beads[fetchIndex];
}
else
{
break
;
}
}
//
===================从后向前拿==================
color
=
m_beads[m_len
-
1
];
if
(color
!=
'
n
'
)
{
retBeadsCount
++
;
}
fetchIndex
=
m_len
-
2
;
nextColor
=
m_beads[fetchIndex];
if
(nextColor
!=
'
n
'
)
{
while
((color
==
nextColor)
||
(nextColor
==
'
w
'
)
||
(color
==
'
w
'
))
{
if
((color
==
'
w
'
)
&&
(nextColor
!=
'
w
'
))
color
=
nextColor;
retBeadsCount
++
;
m_beads[fetchIndex]
=
'
n
'
;
fetchIndex
--
;
if
(fetchIndex
>=
0
)
{
nextColor
=
m_beads[fetchIndex];
}
else
{
break
;
}
}
}
return
retBeadsCount;
}
}
;
//
end class BROKEN_NECKLACE
//
完整的珠子类(环形)
class
NECKLACE
{
private
:
string
m_beads;
//
珠子数据
int
m_len;
//
珠子长度
public
:
//
构造珠子
NECKLACE(
const
string
&
beads)
{
m_beads
=
beads;
m_len
=
m_beads.length();
}
//
给定一个位置,获得从这个位置打断后的项链
BROKEN_NECKLACE Break(
int
breakIndex)
{
string
breakingBeads
=
""
;
for
(
int
i
=
breakIndex; i
<
m_len; i
++
)
breakingBeads
+=
m_beads[i];
for
(
int
i
=
0
; i
<
breakIndex; i
++
)
breakingBeads
+=
m_beads[i];
return
BROKEN_NECKLACE(breakingBeads);
}
//
获得珠子长度
int
GetLength()
{
return
m_len;
}
}
;
//
end class NECKLACE
//
main program start
int
best
=
0
;
//
记录获得的珠子数的最大值
NECKLACE
*
necklace;
void
Init()
{
ifstream fin (
"
beads.in
"
);
int
n;
string
beads;
fin
>>
n;
fin
>>
beads;
necklace
=
new
NECKLACE(beads);
fin.close();
}
void
Run()
{
for
(
int
i
=
0
; i
<
necklace
->
GetLength(); i
++
)
{
BROKEN_NECKLACE bNecklace
=
necklace
->
Break(i);
best
=
max(best,bNecklace.GetBeadsFromBothSides());
}
}
void
Show()
{
ofstream fout (
"
beads.out
"
);
fout
<<
best
<<
endl;
fout.close();
}
void
UnInit()
{
delete necklace;
}
int
main()
{
Init();
Run();
Show();
UnInit();
return
0
;
}
posted on
2008-09-08 18:16
刘永辉
阅读(
561
) 评论(
5
)
收藏
举报
刷新页面
返回顶部