赛码-0726

01串的魔法

思路:虽然标着dp,其实是滑动窗口问题,dp 会超时

import java.util.*;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();
        int k = scanner.nextInt();

        int arr[] = new int[n];
        int max = 0;
        int left = 0;
        int right = 0;
        int cnt = 0;

        for(int i=0;i<n;i++)arr[i] = scanner.nextInt();

        while(right<n){
            if(arr[right]==0)cnt++;

            while(cnt>k){
                if(arr[left]==0)cnt--;
                left++;
            }
            if(right - left + 1 > max)max = right - left + 1;
            right ++ ;
        }
        System.out.println(max);
    }
}

dp解法也写了,先是超空间,优化后又超时间

import java.util.*;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();
        int k = scanner.nextInt();

        int arr[] = new int[n+1];
        int dp[][] = new int[2][k+1];
        int max = 0;

        for(int i=1;i<=n;i++)arr[i] = scanner.nextInt();


        for(int i=1;i<=n;i++){

            dp[1][0] = arr[i]==1?dp[0][0]+1:0;

            for(int j=1;j<=k;j++){
                if(arr[i]==0) dp[1][j] = dp[0][j-1] + 1;
                else dp[1][j] = dp[0][j] + 1;
            }
            max = Math.max(max,dp[1][k]);
            for(int j=0;j<=k;j++){
                dp[0][j] = dp[1][j];
                dp[1][j] = 0;
            }
        }
        System.out.println(max);
    }
}

上台阶

import java.util.*;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();

        int dp[] = new int[101];

        dp[1] = 1;
        dp[2] = 1;

        for(int i = 3;i<=100;i++)
            dp[i] = dp[i-1] + dp[i-2];
        dp[1] = 0;

        for(int i=0;i<n;i++){
            int m = scanner.nextInt();
            System.out.println(dp[m]);
        }
    }
}

triangle

思路:只有斐波那契数列三三之间不能组成三角形,把剩下的都剔除

import java.util.*;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        int fib[] = new int[40];
        fib[0] = 1;
        fib[1] = 1;

        for(int i=2;i<30;i++){
            fib[i] = fib[i-1]+fib[i-2];
        }


        while (scanner.hasNext()){
            int m = scanner.nextInt();
            int cnt  = 0;
            for(int i = 1;i<30;i++){
                if(fib[i]<=m)cnt++;
                else break;
            }
            System.out.println(m-cnt);
        }
    }
}

你可能感兴趣的:(牛客赛码,算法,java,动态规划)