HUST1605 - Gene recombination (BFS)

题意:

有两个长度为N(N<=12)的字符串,字符串由A、C、G、T组成,可以有两种操作

1、将字符串的第一位变成最后一位

2、交换字符串前两位

求将第一个字符串变为第二个字符串的最小次数

 

这是一个简单的BFS,ACGT表示成0123,这样有4^12种状态,BFS一下可得

用bool比用map会快一些

#include<stdio.h>
#include<queue>
#include<map>
#include<string.h>
#include<iostream>
using namespace std;
char st[15];
int s[15],t[15];
int get(char c)
{
    if(c=='A') return 0;
    if(c=='T') return 1;
    if(c=='C') return 2;
    return 3;
}
int main()
{
    int n;
    int i,j,k;
    while(scanf("%d",&n)!=EOF)
    {
        scanf("%s",st);
        for(i=0;i<n;i++) s[i+1]=get(st[i]);
        scanf("%s",st);
        for(i=0;i<n;i++) t[i+1]=get(st[i]);
        int S=0,T=0;
        map<int,int> f;
        for(i=1;i<=n;i++) S*=4,S+=s[i];
        for(i=1;i<=n;i++) T*=4,T+=t[i];
        f[S]=1;
        if(n==1)
        {
            printf("0\n");
            continue;
        }
        queue<int> q;
        q.push(S);
        while(!q.empty())
        {
            int now=q.front();
            q.pop();
            int tp=now;
            for(i=n;i>=1;i--)
                s[i]=tp%4,tp/=4;
            int to=0;
            for(i=2;i<=n;i++) to*=4,to+=s[i];
            to*=4;to+=s[1];
            if(f[to]==0)
            {
                f[to]=f[now]+1;
                q.push(to);
            }
            to=0;
            to=s[2];to*=4;to+=s[1];
            for(i=3;i<=n;i++) to*=4,to+=s[i];
            if(f[to]==0)
            {
                f[to]=f[now]+1;
                q.push(to);
            }
            if(f[T]) break;
        }
        printf("%d\n",f[T]-1);
    }
}

 

posted @ 2016-03-07 15:40  Woo95  阅读(243)  评论(0编辑  收藏  举报