記憶化搜尋 uva-10651-Pebble Solitaire

來源:互聯網
上載者:User

 

題目連結:

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1592

 

題目意思:

給一串-和o組成的字串,你可以把“-oo"變成”--o",可以把“oo-”變成“--o",問最後最少有多少個o.

 

解題思路:
採用記憶化搜素的方法,用map標記是否訪問過,用string的substr提取連續的三個字元,用string的replace得到替換後的字串。

 

代碼:

#include<iostream>#include<cmath>#include<cstdio>#include<cstdlib>#include<string>#include<cstring>#include<algorithm>#include<vector>#include<map>#include<stack>#include<queue>#define eps 1e-6#define INF (1<<20)#define PI acos(-1.0)using namespace std;map<string,bool>mymap;int ans;void dfs(string cur){    if(mymap.find(cur)!=mymap.end()) //如果已經檢查了        return ;    int len=cur.size(),num=0;    for(int i=0;i<len;i++) //查看o的數量        if(cur[i]=='o')            num++;    if(num<ans)        ans=num;    mymap[cur]=true;  //把目前狀態放到map裡    for(int i=0;i<=len-3;i++)    {        if(cur.substr(i,3)=="-oo") //如果有-oo出現,則可以調換        {            string temp=cur;            temp.replace(i,3,"o--");            dfs(temp);        }        if(cur.substr(i,3)=="oo-")        {            string temp=cur;            temp.replace(i,3,"--o");            dfs(temp);        }    }    return ;}int main(){    int n;    scanf("%d",&n);    string temp;    while(n--)    {        map<string,bool>::iterator begin=mymap.begin();        map<string,bool>::iterator end=mymap.end();        mymap.erase(begin,end); //把當前的map清空        ans=INF;        cin>>temp;        dfs(temp);        printf("%d\n",ans);    }    return 0;}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.