XJOI 1210 二項式展開 題解

時間:1s 空間:256M

題目描述:

輸出(a+b)^n的展開式

輸入格式:

輸入一行,包含一個整數n

輸出格式:

見樣例輸出,注意空格的使用

樣例輸入1:

2

樣例輸出1:

(a+b)^2 = a^2 + 2*a*b + b^2

樣例輸入2:

3

樣例輸出2:

(a+b)^3 = a^3 + 3*a^2*b + 3*a*b^2 + b^3

約定:

0<=n<=30

提示:

此題顯然要用到二項式定理,需要一點數學基礎。說得通俗一點,就是楊輝三角(當然還有其他解法)。具體的每一項的係數可以遞推出來。當n=x時,係數從左往右剛好是楊輝三角的x+1行。當然,這道題還要特判,就是n=0的時候,很容易漏掉。

代碼:

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#define N 40
int a [ N ] [ N ] , n ;
using namespace std ;
int main ( )
{
    scanf ( "%d" , & n ) ;
    memset ( a , 0 , sizeof ( a ) ) ;
    a [ 1 ] [ 1 ] = 1 ;
    for ( int i = 2 ; i <= n + 1 ; i ++ )
        for ( int j = 1 ; j <= i ; j ++ ) 
            a [ i ] [ j ] = a [ i - 1 ] [ j ] + a [ i - 1 ] [ j - 1 ] ;
    printf ( "(a+b)^%d = " , n ) ;
    if ( n == 0 ) printf ( "1" ) ;
    else for ( int i = 1 ; i <= n + 1 ; i ++ )
        {
            if ( a [ n + 1 ] [ i ] != 1 ) printf ( "%d*" , a [ n + 1 ] [ i ] ) ;
            if ( i != n + 1 ) printf ( "a" ) ;
            if ( i < n ) printf ( "^%d" , n - i + 1 ) ;
            if ( i != 1 && i != n + 1 ) printf ( "*" ) ;
            if ( i != 1 ) printf ( "b" ) ;
            if ( i > 2 ) printf ( "^%d" , i - 1 ) ;
            printf ( " " ) ;
            if ( i != n + 1 ) printf ( "+" ) ;
            printf ( " " ) ;
        }  
    return 0 ;
}

當然,上面的代碼還可以升級,節省一點空間,將二維數組改一位數組。雖然這麼改意義不大,都能過,但畢竟是一種思想。

#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <algorithm>
#include <cmath>
#define N 40
int a [ N ] , n ;
using namespace std ;
int main ( )
{
    scanf ( "%d" , & n ) ;
    memset ( a , 0 , sizeof ( a ) ) ;
    a [ 1 ] = 1 ;
    for ( int i = 2 ; i <= n + 1 ; i ++ )
        for ( int j = i ; j >= 1 ; j -- ) 
            a [ j ] = a [ j ] + a [ j - 1 ] ;
    printf ( "(a+b)^%d = " , n ) ;
    if ( n == 0 ) printf ( "1" ) ;
    else for ( int i = 1 ; i <= n + 1 ; i ++ )
        {
            if ( a [ i ] != 1 ) printf ( "%d*" , a [ i ] ) ;
            if ( i != n + 1 ) printf ( "a" ) ;
            if ( i < n ) printf ( "^%d" , n - i + 1 ) ;
            if ( i != 1 && i != n + 1 ) printf ( "*" ) ;
            if ( i != 1 ) printf ( "b" ) ;
            if ( i > 2 ) printf ( "^%d" , i - 1 ) ;
            printf ( " " ) ;
            if ( i != n + 1 ) printf ( "+" ) ;
            printf ( " " ) ;    //行末空格沒關係的
        }    
    return 0 ;
}

相關鏈接:

XJOI 題解小全:
https://blog.csdn.net/zj_mrz/article/details/80949787

XJOI 3265 Climb the stairs 爬樓梯 題解:
https://blog.csdn.net/zj_mrz/article/details/80970052

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章