UVA 12380 Glimmr in Distress --DFS

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   

題意:給你一串數字序列,只包含0,1,2,一路掃描過去,遇到2則新開一個2x2的矩陣,然後如果掃到0或1就將其填入矩陣,注意不能四個方格全是0或者全是1,那樣跟一個方格沒區別,所以21111這種是不可能的,問根據串的數字先後順序可不可能構造一個矩陣出來,正好把數字都填完,如果可以,輸出該矩陣的大小,2^n*2^n的形式輸出。

分析:其實就是遞迴求解,首先判斷第一個數是不是2,不是則說明沒有分塊,所以長度必須是1,數字可以為0或1,如果是則dfs,每次遇到2,則dfs下一層,並從下一個下標開始,用flag[4]儲存接下來的四個數,以判斷是否出現一樣的四個數。返回到第0層時,因為第一個數是2,所以j=0的時候就dfs了下去,所以全部符合的話,第0層的j+=1變為1,所以如果第0層j!=1,說明肯定有多的,返回false。

代碼:

#include <iostream>#include <cstdio>#include <cstring>#include <cmath>#include <algorithm>using namespace std;#define N 2517char ss[N];int now,len,maxi;bool dfs(int dep){    now++;         //位置移動    maxi = max(maxi,dep);    int j = 0;    int tag[4];    memset(tag,-1,sizeof(tag));    for(j=0;j<4&&now<len;j++,now++)    {        tag[j] = ss[now]-‘0‘;        if(tag[j] != 2)            continue;        if(!dfs(dep+1))            return 0;    }    if(dep > 0)    {        if(tag[0] == -1 || tag[1] == -1 || tag[2] == -1 || tag[3] == -1)            return 0;        if(tag[0] == tag[1] && tag[0] == tag[2] && tag[0] == tag[3] && tag[0] != 2)  //四個相同的組成一個            return 0;    }    else if(j != 1)  //dep == 0        return 0;    now--;    //位置還原    return true;}int main(){    int t,i;    scanf("%d",&t);    while(t--)    {        scanf("%s",ss);        len = strlen(ss);        if(ss[0] != ‘2‘)        {            if(len != 1)                puts("Not Possible");            else                puts("2^0*2^0");        }        else        {            maxi = 0;            now = -1;            if(dfs(0))                printf("2^%d*2^%d\n",maxi,maxi);            else                puts("Not Possible");        }    }    return 0;}
View Code

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.