HDU 2125 Local area network

來源:互聯網
上載者:User

標籤:style   blog   http   color   os   io   for   ar   art   

簡單DP,N×M的網格其中有一條邊壞掉了,問從起點到終點的放法數

有兩種方法,一種是DP很好理解

 

 1 //#define LOCAL 2 #include <cstdio> 3 #include <cstring> 4  5 int dp[42][42]; 6 bool flag[42][42]; 7  8 int main(void) 9 {10     #ifdef LOCAL11         freopen("2125in.txt", "r", stdin);12     #endif13 14     int r, c;15     while(scanf("%d%d", &r, &c) == 2)16     {17         int y1, x1, y2, x2;18         scanf("%d%d%d%d", &y1, &x1, &y2, &x2);19         dp[0][1] = 1;20         memset(flag, false, sizeof(flag));21         flag[x1+1][y1+1] = flag[x2+1][y2+1] = true;22         for(int i = 1; i <= r; ++i)23             for(int j = 1; j <= c; ++j)24             {25                 dp[i][j] = dp[i-1][j] + dp[i][j-1];26                 if(flag[i][j])27                 {28                     if(flag[i][j-1])29                         dp[i][j] -= dp[i][j-1];30                     if(flag[i-1][j])31                         dp[i][j] -= dp[i-1][j];32                 }33             }34         printf("%d\n", dp[r][c]);35     }36     return 0;37 }
代碼君

 

第二種,用數學公式

如果沒有壞邊的話,總放法數是CN-1(M+N-2) 

因為每種方法都要走(M+N-2)步,向上走N-1步,向下走M-1步

現在考慮一條壞邊,那麼就計算經過這條壞邊的方案數然後從總數裡面減去即可

經過壞邊的放法數就是從起點到(x1, y1)的放法數×從(x2, y2)到終點的放法數

 1 #define LOCAL 2 #include <algorithm> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6  7 long long c(long long m, long long n) 8 { 9     if(m==0 || n==0)10         return 1;11     n = min(n, m-n);12     long long ans = 1;13     for(int i = 0; i < n; ++i)14         ans = ans * (m-i) / (1+i);15     return ans;16 }17 18 int main(void)19 {20     #ifdef LOCAL21         freopen("2125in.txt", "r", stdin);22     #endif23 24     int n, m;25     while(scanf("%d%d", &n, &m) == 2)26     {27         int x1, y1, x2, y2;28         scanf("%d%d%d%d", &x1, &y1, &x2, &y2);29         if(x1+y1 > x2+y2)30         {31             int t = x1;32             x1 = x2, x2 = t;33             t = y1;34             y1 = y2, y2 = t;35         }36         printf("%lld\n", c(m+n-2, m-1) - c(x1+y1, x1) * c(m+n-2-x2-y2, m-1-x2));37     }38     return 0;39 }
代碼君

 

HDU 2125 Local area network

聯繫我們

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