Blue Bridge Zhenti: Yang Hui's Triangle (thinking + two points)

text

Topic description

insert image description here

Topic ideas and codes

The basic properties of Yanghui triangle: left and right symmetry, so as long as the number that appears in the right half of Yanghui triangle will appear in the left half, and the position is symmetrical, so the answer must be in the left half

insert image description here

Idea: For each oblique row and vertical row, it increases sequentially from top to bottom. It needs to be clear that all numbers will appear in the Yanghui triangle, such as x, there must be C(x,1) corresponding to x , so don't worry about whether there is a solution, but we need to find the topmost position with the value x and we need to enumerate from bottom to top , because if x appears at the position (i, j) for the first time, then this The numbers in the upper left, upper and upper right of the position will be smaller than x, so we can enumerate the oblique rows, and use dichotomy to enumerate the positions that appear in each oblique row. Note that the enumeration is from bottom to top. According to the above property 2, the calculation method of Yang-Hui's triangle optimized by the number of combinations can be obtained.
Code:

#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
const ll maxn=1e5+10;
ll n;
ll C(ll x,ll y){
    
    //计算组合数
    ll ans=1;
    for(int i=x,j=1;j<=y;j++,i--){
    
    
        ans=ans*i/j;
        if(ans>n)return ans;
    }
    return ans;
}
ll cha(ll k){
    
    
    ll l=2*k,r=max(n,l);
    //二分找出结果
    while(l<r){
    
    
        ll mid=(l+r)>>1;
        if(C(mid,k)>=n){
    
    
            r=mid;
        }else{
    
    
            l=mid+1;
        }
    }
    if(C(l,k)!=n)return 0;
    ll ans=l*(l+1)/2+k+1;//用等差数列进行求在这行之前所有数字
    cout<<ans;
    return 1;
}
int main(){
    
    
    cin>>n;
    ll ans=n;
    for(int i=16;;i--){
    
    
        if(cha(i))break;
    }

	return 0;
}

Epilogue


"If you are undecided, you can ask the spring breeze, and if the spring breeze does not speak, you will follow your heart" means: if you are hesitant about something, ask the spring breeze how to do it. . "If you are undecided, you can ask the spring breeze. If the spring breeze does not speak, you will follow your heart." The sentence comes from the "Jianlai" written by the Internet writer "Fenghuo Opera Princes". The original text is: "If you are undecided, you can ask the spring breeze. Follow your heart".

insert image description here


Guess you like

Origin blog.csdn.net/weixin_46627433/article/details/123945269