[stetch cup · Cloud Bridge · algorithm training camp] week 3

Posted by cap2cap10 on Tue, 25 Jan 2022 03:11:20 +0100

1. Fibonacci sequence
Title Description
Fibonacci numbers are usually represented by F(n), and the sequence formed is called Fibonacci sequence. The sequence starts with 1 and 1, and each subsequent number is the sum of the first two numbers. That is:

F(0) = 1,F(1) = 1
F(n) = F(n - 1) + F(n - 2), where n > 1
Here you are n, please calculate F(n).

#include<stdio.h>
int F(int n)
{
	if (n == 1 || n == 2)
	{
		return 1;
	}
	else
	{
		return F(n - 1) + F(n - 2);
	}
}
int main()
{
	int n,f;
	scanf("%d", &n);
	f = F(n);
	printf("f=%d", f);
	return 0;
} 

2. N th teponacci number
Title Description
The teponacci sequence Tn is defined as follows:
T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 when n > = 0
Here is the integer n. please return the value of the nth teponacci number Tn.

Example 1:

Input: n = 4
Output: 4
Explanation:
T_3 = 0 + 1 + 1 = 2
T_4 = 1 + 1 + 2 = 4
Example 2:

Input: n = 25
Output: 1389537

 

#include<stdio.h>
int F(int n)
{
	int a=0,b=1,c=1,d=0;         //Assign values to the first three items
	if (n == 0)
	{
		return 0;
	}else if(n <= 2){
		return 1;
	}
	while(n>2){
		d=a+b+c;
		a=b;
		b=c;
		c=d;
		n--;			
	} 
	return d;
}
int main()
{
	int n,f;
	scanf("%d",&n);
	f=F(n);
	printf("%d",f);
	return 0;
}

3. Climb stairs
Title Description

Suppose you are climbing stairs. You need n steps to reach the roof.
You can climb one or two steps at a time. How many different ways can you climb to the roof?

Example 1:
Input: 2
Output: 2
Explanation: there are two ways to climb to the roof.
1. 1st order + 1st order
2. Second order
Example 2:
Input: 3
Output: 3
Explanation: there are three ways to climb to the roof.
1. 1st order + 1st order + 1st order
2. 1st order + 2nd order
3. 2nd order + 1st order

#include<stdio.h>
int F(int n)
{
	if (n == 1)
	{
		return 1;
	}
	if(n == 2){
		return 2;
	}
	if(n > 2){
		return F(n - 1) + F(n - 2);
	}
}
int main()
{
	int n,f;
	scanf("%d", &n);
	f = F(n);
	printf("f=%d", f);
	return 0;
} 

4. Use the minimum cost to climb stairs
Title Description
Give you an integer array cost, where cost[i] is the cost of climbing up the ith step of the stairs. Once you pay this fee, you can choose to climb up one or two steps.

You can choose to climb the stairs from the steps with subscript 0 or subscript 1.

Please calculate and return the minimum cost to reach the top of the stairs.

Example 1:

Input: cost = [10,15,20]
Output: 15
Explanation: you will start with a step with a subscript of 1.

Pay 15 and climb two steps up to the top of the stairs.
The total cost is 15.
Example 2:
Input: cost = [1100,1,1,1100,1,1100,1]
Output: 6
Explanation: you will start with a step with a subscript of 0.

Pay 1 and climb up two steps to the step with subscript 2.
Pay 1 and climb up two steps to the step with subscript 4.
Pay 1, climb two steps up to the step with subscript 6.
Pay 1 and climb up one step to the step with subscript 7.
Pay 1, climb two steps up to the step with subscript 9.
Pay 1, climb one step up to the top of the stairs.
The total cost is 6.
 

int minCostClimbingStairs(vector<int>& cost) {        
 
	vector<int> M(cost.begin(),cost.begin()+2);        
	
	for(int i = 2;i<static_cast<int>(cost.size());i++)        
	{            
		M.push_back(cost[i] + min(M[i-1] , M[i-2]));        
	}        
	
	return min(M[cost.size()-1],M[cost.size()-2]);    
}

5. The best time to buy and sell stocks
Title Description
Given an array of prices, its ith element price [i] represents the price of a given stock on day I.
You can only choose to buy this stock one day and sell it on a different day in the future. Design an algorithm to calculate the maximum profit you can make.
Return the maximum profit you can make from this transaction. If you can't make any profit, return 0.

Example 1:

Input: [7,1,5,3,6,4]
Output: 5
Explanation: buy on day 2 (stock price = 1) and sell on day 5 (stock price = 6). Maximum profit = 6-1 = 5.
Note that the profit cannot be 7-1 = 6, because the selling price needs to be greater than the buying price; At the same time, you can't sell stocks before buying.
Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: in this case, no transaction is completed, so the maximum profit is 0.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.empty())
            return 0;
        int cnt=0;
        for (int i=0;i<prices.size()-1;++i)
        {
            if(prices[i]<prices[i+1])
                cnt += prices[i+1]-prices[i];
        }
        return cnt;
    }
};

6. Longest common subsequence
Title Description
Given two strings text1 and text2, returns the length of the longest common subsequence of the two strings. If there is no common subsequence, 0 is returned.
The subsequence of a string refers to such a new string: it is a new string composed of the original string after deleting some characters (or not deleting any characters) without changing the relative order of characters.
For example, "ace" is a subsequence of "abcde", but "aec" is not a subsequence of "abcde".
The common subsequence of two strings is the subsequence shared by the two strings.

Example 1:

Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: the longest common subsequence is "ace", and its length is 3.
Example 2:

Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: the longest common subsequence is "abc", and its length is 3.
Example 3:

Input: text1 = "abc", text2 = "def"
Output: 0
Explanation: two strings have no common subsequence and return 0.
 

#include <stdio.h>
 
void LSCLength(char a[],char b[],int c[11][10],int lsc[11][10],int la,int lb)
{
	for(int i=0;i<=la;i++)	lsc[0][i]=0;
	for(int i=0;i<=lb;i++)	lsc[i][0]=0;
	for(int i=1;i<=la;i++)
	{
		for(int j=1;j<=lb;j++){
			if(a[i-1]==b[j-1])
			{
				lsc[i][j]=lsc[i-1][j-1]+1;
				c[i][j]=1;
			}
			else if(lsc[i-1][j]>=lsc[i][j-1])
			{
				lsc[i][j]=lsc[i-1][j];
				c[i][j]=2;
			}
			else{
				lsc[i][j]=lsc[i][j-1];
				c[i][j]=3;
			}
		}
	}
 
	
}
void LSC(int i,int j,char a[],int c[11][10]) 
{
	if(i==0 || j==0)	return;
	if(c[i][j]==1)
	{
		LSC(i-1,j-1,a,c);
		printf("%3c  ",a[i-1]);
	}
	else if(c[i][j]==2)
	{
		LSC(i-1,j,a,c);
	}
	else
	{
		LSC(i,j-1,a,c);
	}
	
}
int main(int argc, char** argv) {
	char a[10]={'d','i','d','a','c','t','i','c','a','l'};
	char b[9]={'a','d','v','a','n','t','a','g','e'};
	int c[11][10]={0};
	int lsc[11][10]={0};
	LSCLength(a,b,c,lsc,10,9);
	for(int i=0;i<=10;i++)
	{
		for(int j=0;j<=9;j++)
		{
			printf("%d  ",lsc[i][j]);
		}
		printf("\n");
	}
	printf("Length:%d\n Comparative situation\n",lsc[10][9]);
	
	for(int i = 0;i<11;i++){
		for(int j = 0;j<10;j++){
			printf("%3d",c[i][j]);
		}
		printf("\n");
	}
	LSC(10,9,a,c);
	return 0;
} 

7. Yanghui triangle

#include<iostream>
using nameapace std;
int N;
long long C(int n,int m){
	long long t = 1;
	for(int i =0;i<m;i++){
		t= t*(n-i)/(i+1);
		if(t>N)
			return t;
	}
	return t;
}
bool find(int L,int R,int x){
	long long ans = 0,M = 0;
	while(R>=L){
		int T = (R+L)>>1;
		ans = C(T,x);
		if(ans<=N)
			M = T,L=T+1;
		else
			R = T - 1;
	}
	if(C(M,x)==N){
		cout<<(1+M)*M/2 + x + 1;
		return true;
	}
	return false;
}
int main(){
	cin >> N;
	if(N == 1)
		cout<<1;
	else 
		for(int i=17;i>0;i--)
			if(find(i*2,N,i))
				break;
	reutrn 0;
}

 

8. Node selection

Title Description

There is a tree with n nodes, and each node in the tree has a positive integer weight. If a point is selected, no point adjacent to it in the tree can be selected. What is the maximum weight sum of the selected points?
sample input
5
1 2 3 4 5
1 2
1 3
2 4
2 5
sample output
12

#include<iostream>
using namespace std;
const int M = 100;
int max(int x,int y){
	return x<y?y:x;
}
int a[M+5],p[M+5];
int son[M+5][M+5];
bool bo[M+5];
int find(int x,bool can){
	if(!p[x])
		return can?a[x]:0;
	int ans = 0;
	for(int i = 0;i<p[x];i++){
		ans += find(son[x][i],true);
	}
	if(can){
		int t = a[x];
		for(int i = 0;i<p[x];i++)
			t += find(son[x][i],false);
		ans = max(ans,t);
	}
	return ans;
}
int main(){
	cin>>n;
	for(int i =1;i <= n; i++){
		cin>>a[i];
	}
	for(int i =1;i < n; i++){
		int t1,t2;
		cin>>t1>>t2;
		son[t1][p[t1]++]=t2;
	}
	cout<<find(1,true);
return 0;	
}

9. Fall resistance index
Title Description
Planet x has many towering towers, which can be used for fall resistance test.
The height of each floor of the tower is the same. Their first floor is not the ground, but equivalent to our second floor.
Their ground level is 0. If the mobile phone is not broken when dropped from the 7th floor, but the 8th floor is broken, then
Mobile phone fall resistance index = 7.
In particular, if the mobile phone is broken when dropped from the first floor, the fall resistance index = 0.
If it is not broken when it is thrown on the nth floor at the highest level of the tower, the falling resistance index = n.
In order to speed up the test progress, three mobile phones of each model were sampled to participate in the test.
The problem is: if the height n of the test tower is known and the best strategy is adopted, under the worst luck
How many tests are needed to determine the fall resistance index of the mobile phone?
 

#include<iostream>
using namespace std;
int dp[2][10001];
int main(){
	int n;
	cin>>n;
	int i=0;
	while(dp[1][i]<n){
		i++;
		dp[0][i]=dp[1][i-1]+i;
		dp[1][i]=dp[1][i-1]+dp[0][i-1]+1;
	}
	cout<<i<<endl;
return 0;	
}

10.K good number
Title Description
If any two adjacent digits in the K-ary representation of a natural number N are not adjacent numbers, then
Let's say this number is a good number K. Find the number of K good numbers in L-bit k-ary numbers. For example, K = 4, L = 2
At the time of, all K good numbers are 11, 13, 20, 22, 30, 31 and 33, a total of 7. Because the number is very small
Large, please output the value after taking the mold of 100000007.
Input format
The input contains two positive integers, K and L.
Output format
Output an integer representing the value of the answer after modulo 100000007.
sample input
4 2
sample output
7
 

#include<stdio.h>
int main(){
	int k,l,i,j,m,sum;//Because the maximum value of int (32-bit) is 2147483647
	//Therefore, the remainder of 1000000007 will not overflow in each calculation 
	scanf("%d%d",&k,&l);
	if(l==1){
		printf("%d",k);//Special discussion when L=1
	}
	else{
	 	int dp[l+1][k];//Bit 0 does not start with bit 1, so it is l+1 for convenience of understanding 
		for(i=0;i<k;i++){
			dp[1][i]=1;//Initialize 1 digit to 1 
		}
		for(i=2;i<l+1;i++){//Here i stands for i bit 
			for(j=0;j<k;j++){//j stands for the number beginning with j 
				sum=0;//Initialize sum 
				for(m=0;m<k;m++){//Traverse all cases of i-1 bit 
					if(m-j!=1&&j-m!=1){//Non adjacent entry 
						sum=(sum+dp[i-1][m])%1000000007;
					}
				}
				dp[i][j]=sum;//Assign a value to the location 
			}
		}
		sum=0;//Initialize sum 
		for(i=1;i<k;i++){//When the number of bits exceeds 1, 0 cannot be used as the beginning, so it is rounded off. When k=1, it cannot enter the cycle directly, so 0 is output
			sum=(sum+dp[l][i])%1000000007;//Add to get the result 
		}
		printf("%d",sum);
	}
	return 0;
}

Topics: C C++ Algorithm