[meet in the middle]String Coloring

本文探讨了在给定长度为2N的字符串中,如何计算满足特定条件的字符串涂色方式数量。条件为从左至右读取的红色字符字符串等于从右至左读取的蓝色字符字符串。通过meet-in-the-middle搜索策略,文章提供了详细的算法实现,包括输入输出格式、示例和源代码。
题目描述
You are given a string S of length 2N consisting of lowercase English letters.
There are 22N ways to color each character in S red or blue. Among these ways, how many satisfy the following condition?
The string obtained by reading the characters painted red from left to right is equal to the string obtained by reading the characters painted blue from right to left.
Constraints
1≤N≤18
The length of S is 2N.
S consists of lowercase English letters.

 

输入
Input is given from Standard Input in the following format:
N
S

 

输出
Print the number of ways to paint the string that satisfy the condition.

 

样例输入

复制样例数据

4
cabaacba
样例输出
4

 

提示

There are four ways to paint the string, as follows:
cabaacba
cabaacba
cabaacba
cabaacba

思路:meet in the middle搜索
#include <iostream>
#include<cstdio>
#include<string>
#include<map>
typedef long long ll;
using namespace std;

char s[20];
map< pair<string,string>,ll > mp;

int main()
{
    ll n;scanf("%lld",&n);
    scanf("%s",s);
    for(ll i=0;i<=(1<<n)-1;i++){
        string a,b;
        for(ll j=0;j<n;j++){
            if((i>>j)&1) a+=s[j];
            else b+=s[j];
        }
        mp[make_pair(a,b)]++;
    }
    ll ans=0;
    for(ll i=0;i<=(1<<n)-1;i++){
        string a,b;
        for(ll j=0;j<n;j++){
            if((i>>j)&1) a+=s[2*n-1-j];
            else b+=s[2*n-1-j];
        }
        ans+=mp[make_pair(a,b)];
    }
    printf("%lld\n",ans);
    return 0;
}
View Code

 

 

转载于:https://www.cnblogs.com/lllxq/p/10365959.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值