網易筆試:素數,字典序,丟棄價值

2020-08-13 12:30:11

素數

在这里插入图片描述

#include <stdio.h>

int main()
{
   /* 我的第一個 C 程式 */
   int n;
    scanf("%d",&n);
    int a[n];
    for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
	int sum=0;
	for(int i=0;i<n;i++)
	{
	 sum=sum+a[i]/2;
	}
   printf("%d",sum);
   
   return 0;
}

字典序

在这里插入图片描述

#include <cstdio>
#include <cstring>
#include <iostream>
#include <set>
#include <vector>

using namespace std;

const int maxn = 1e5 + 5;

int A[maxn];
int B[maxn];
bool C[maxn];

int main()
{
    int n,m;
    cin >> n >> m;

    memset(C,0,sizeof(C));

    for (int i = 0; i < m; ++i) {
        cin >> A[i];
        C[A[i]] = true;
    }

    int k = 0;
    for (int i = 1; i <= n; ++i) {
        if (!C[i]) {
            B[k++] = i;

        }
    }

    int i,j;
    for (i = 0, j = 0; i < m && j < k; ) {
        if (A[i] < B[j]) {
            cout << A[i++] << endl;

        }
        else {
            cout << B[j++] << endl;

        }
    }

    while( i < m ) {
        cout << A[i] << endl;
        ++i;
    }

    while( j < k) {
        cout << B[j] << endl;
        ++j;
    }

    return 0;
}

丟棄價值

在这里插入图片描述
在这里插入图片描述

import java.util.Scanner;

public class Test {
    static int NINF = Integer.MIN_VALUE / 3;
    static Integer[][] memo;
    public static int tallestBillboard(int[] rods) {
        int N = rods.length;
        // "memo[n][x]" will be stored at memo[n][5000+x]
        // Using Integer for default value null
        memo = new Integer[N][10001];
        return (int) dp(rods, 0, 5000);
    }

    public static int dp(int[] rods, int i, int s) {
        if (i == rods.length) {
            return s == 5000 ? 0 : NINF;
        } else if (memo[i][s] != null) {
            return memo[i][s];
        } else {
            int ans = dp(rods, i+1, s);
            ans = Math.max(ans, dp(rods, i+1, s-rods[i]));
            ans = Math.max(ans, rods[i] + dp(rods, i+1, s+rods[i]));
            memo[i][s] = ans;
            return ans;
        }
    }


    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int T = scanner.nextInt();
        for(int i=0;i<T;i++) {
            int n=scanner.nextInt();
            int [] a = new int[n];
            int sum=0;
            for(int j=0;j<n;j++) {
                a[j]=scanner.nextInt();
                sum=sum+a[j];
            }
            System.out.println(sum-2*tallestBillboard(a));
        }
    }
}