Algorithm notes score matrix

topic

We define the following matrix:
1/1 1/2 1/3
1/2 1/1 1/2
1/3 1/2 1/1
The elements on the diagonal of the matrix are always 1/1, and the scores on both sides of the diagonal The denominator of increases one by one.
Request the sum of this matrix.

Input

The input contains multiple sets of test data. Each row is given an integer N (N<50000), which means that the matrix is ​​N*N. When N=0, the input ends.
Output

The answer is output, and the result is kept to 2 decimal places.

Ideas

1.Time Limit Exceed 50

  • Calculate the number of matrices each time, and hit the table
  • Find the matrix value of n by deriving the matrix value of n-1
  • Finally got the result

Code:

#include <stdio.h>
#include <iostream>
#include <vector>
using namespace std;
vector<double> save;
double count(int n){
    
    
    if(n==1){
    
    
        if(save.size()<n)
            save.push_back(1);
        return 1;
    }
    else{
    
    
        double res=0;
        if(save.size()>=n)
            res=save[n-1];
        else{
    
    
            double sum=0;
            for(int i=2;i<=n;i++){
    
    
                sum+=1/(double)i;
            }
            res=count(n-1)+2*sum+1;
            save.push_back(res);
        }
        return res;
    }
}
int main(){
    
    
    
    int n=0;
    while(scanf("%d",&n)!=EOF){
    
    
        if(n==0)
            break;
        double res=count(n);
        printf("%.2lf\n",res);
    }
    return 0;
}

2.Accepted100

  • 1/1

Calculation: 1

1/1 1/2
1/2 1/1

Calculation: [(2*1+1*1/2)-2*1] 2+2 1

1/1 1/2 1/3
1/2 1/1 1/2
1/3 1/2 1/1

Calculation: [(3*1+2*1/2+1*1/3)-3*1]*2+3*1

Ideas

  • First calculate the upper triangle (not the diagonal)
  • Then x2 (because there are two upper and lower matrix triangles)
  • Finally add the diagonal

Code:

#include <stdio.h>
#include <iostream>
using namespace std;

int main(){
    
    
    
    int n=0;
    while(scanf("%d",&n)!=EOF){
    
    
        if(n==0)
            break;
        double res=0;
        for(int i=0;i<n;i++)
            res+=(n-i)*1.0/(1.0+i);
        res-=n;
        res*=2;
        res+=n;
        printf("%.2lf\n",res);
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/Cindy_00/article/details/108690917
Recommended