HDU 1503 Advanced Fruits

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   for   2014   

求最短公用祖先,是最長公用子序列的變形。

在DP的同時記錄下路徑,然後遞迴回去輸出即可。

如果碰到公用的,只輸出一次。

 

以第一個範例為例:

圖中數字是最大公用子段的長度,下標代表路徑。

帶底線的是遞迴時所走的路徑。

 

 1 //#define LOCAL 2 #include <iostream> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6  7 char s1[205], s2[205]; 8 int path[205][205], dp[205][205]; 9 10 void Print(int i, int j)11 {12     if(i == 0 && j == 0)    return;13     if(i == 0 && j != 0)14     {15         Print(i, j-1);16         printf("%c", s2[j-1]);17     }18     else if(i != 0 && j == 0)19     {20         Print(i-1, j);21         printf("%c", s1[i-1]);22     }23     else if(path[i][j] == 0)24     {25         Print(i-1, j-1);26         printf("%c", s1[i-1]);27     }28     else if(path[i][j] == 1)29     {30         Print(i-1, j);31         printf("%c", s1[i-1]);32     }33     else34     {35         Print(i, j-1);36         printf("%c", s2[j-1]);37     }38 }39 40 int main(void)41 {42     #ifdef LOCAL43         freopen("1503in.txt", "r", stdin);44     #endif45 46     while(cin >> s1 >> s2)47     {48         int len1, len2;49         len1 = strlen(s1);50         len2 = strlen(s2);51         int i, j;52         for(i = 1; i <= len1; ++i)53             for(j = 1; j <= len2; ++j)54             {55                 if(s1[i-1] == s2[j-1])56                 {57                     dp[i][j] = dp[i-1][j-1] + 1;58                     path[i][j] = 0;59                 }60                 else if(dp[i-1][j] > dp[i][j-1])61                 {//從上邊來62                     dp[i][j] = dp[i-1][j];63                     path[i][j] = 1;64                 }65                 else66                 {//從左邊來67                     dp[i][j] = dp[i][j-1];68                     path[i][j] = 2;69                 }70             }71 72         Print(len1, len2);73         printf("\n");74     }75     return 0;76 }
代碼君

 

聯繫我們

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