EOJ1854 Broken Necklace 枚举

来源:互联网 发布:网站域名注册证书查询 编辑:程序博客网 时间:2024/06/13 09:43

题意就是一个项链从某一个位置断开,从断开的两段开始搜索,同样颜色的珠子可以取下来,其中白色可以看成红色或者蓝色。因为数据量少,可以枚举每一个点作为断点,算出答案。具体代码如下:

#include <iostream>#include <set>#include <cstdlib>#include <cstdio>#include <utility>#include <cmath>#include <cstring>#include <algorithm>#include <map>#define maxn 10000+5#define INF 0x3fffffusing namespace std;typedef long long LL;typedef pair<int, int> pii;map<pii, int> M;int vis[maxn];//判断某一个位置是否搜索过             //是为了防止这种情况wwrr dd,这个ww可能被搜索两次int cal(string necklace, int break_point){    int len = necklace.length();    int i = break_point;    int j = (break_point + 1) % len;    int cnt1 = 0, cnt2 = 0;    char flag = '\0';    int ok = 0;    //在搜索rrww bbb这种情况时,从w开始往左边搜索,刚开始颜色还未确定    //所以用一个不会出现的字符flag = '\0'来表示当前颜色,等搜索到r的时候,颜色就确定了    //flag就变成了r    while ((flag == '\0' || necklace[i] == flag || necklace[i] == 'w')&& !vis[i])    {        if (!ok && necklace[i] != 'w')        {            flag = necklace[i];            ok = 1;        }        cnt1++;        vis[i] = 1;        i = (i - 1 + len) % len;//项链是循环的,所以用%    }    flag = '\0';    ok = 0;    while ((flag == '\0' || necklace[j] == flag || necklace[j] == 'w')&& !vis[j])    {        if (!ok && necklace[j] != 'w')        {            flag = necklace[j];            ok = 1;        }        cnt2++;        vis[j] = 1;        j = (j + 1) % len;    }    return cnt1 + cnt2;}int solve(string necklace){    int len  = necklace.length();    int ans = 0;    for (int i = 0; i < len; i++)//对每个断点枚举    {        memset(vis, 0, sizeof(vis));        ans = max(ans, cal(necklace, i));    }    return ans;}int main(){    //freopen("Input.txt", "r", stdin);    int n;    string necklace;    scanf("%d", &n);    cin >> necklace;    printf("%d\n",solve(necklace));    return 0;}


0 0
原创粉丝点击