腾讯笔试(开发)——20190405

(在下只是个搬运工)

1.

m的范围非常大,如果DP的话就只能看能否把m这一维压缩,然而这是比较困难的。

首先考虑无解的情况,很显然,如果没有1就无解。只要有1就一定有解,因为每种硬币是无限多的。

注意到大面值硬币是凑不出小面值的,但如果我们要硬币尽量少,大面值的又不能太少。所以按面值从小到大的顺序讨论,尽量用已经选的硬币凑成大面值硬币的面值-1,如果不能恰好凑成就多用一个。
--------------------- 
原文:https://blog.csdn.net/rgnoh/article/details/78403872 

#include<stdio.h>
#include<algorithm>
#include<cmath>
using namespace std;

int M,N,A[105],Ans;

int main()
{
    int i,x,tot=0,t;
    //tot表示当前可以凑成的最大面值,且tot以下的都能凑成
    scanf("%d%d",&M,&N);
    for(i=1;i<=N;i++)scanf("%d",&A[i]);

    A[N+1]=M+1;
    sort(A+1,A+N+2);
    if(A[1]!=1)return puts("-1"),0;//没有1则无解

    for(i=2;i<=N+1&&A[i]<=M+1;i++)//注意有可能出现M比某种硬币的面值更小
    {
        if(A[i]-1<=tot)continue;
        t=ceil(1.0*(A[i]-1-tot)/(A[i-1]));//向上取整,因为如果无法恰好凑成就多用一个
        Ans+=t;
        tot+=A[i-1]*t;
    }

    printf("%d",Ans);
}

2.

给定一个仅包含0或1的字符串,现在可以对其进行一种操作:当有两个相邻的字符其中一个是0,另一个是1的时候,可以消除掉这两个字符。这样的操作可以一直进行下去直到找不到相邻的0和1为止。问这个字符串经历了操作以后的最短长度。

输入:

第一行一个整数,n(1<=n<=2*10^5),表示所给字符串的长度。

第二行是所给的字符串。

输出:

一个整数,表示问题的解。

import java.util.*;
public class Main18 {
	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		int n=in.nextInt();
		String str=in.next();
		List<Character> list=new ArrayList<>();
		for(int i=0;i<str.length();i++) {
			if(list.size()==0) {
				list.add(str.charAt(i));
			}else if(list.get(list.size()-1)==str.charAt(i)) {
				list.add(str.charAt(i));
			}else {
				list.remove(list.size()-1);
			}
		}
		System.out.println(list.size());
	}
}

3.

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int monster = sc.nextInt();
        long[] power = new long[monster];
        int[] money = new int[monster];
        for(int i=0; i<monster; i++){
            power[i] = sc.nextInt();
        }
        for(int i=0; i<monster; i++){
            money[i] = sc.nextInt();
        }

        hire(power, money, 0, monster, 0, 0, true);
        System.out.print(minM);
    }

    static int minM = Integer.MAX_VALUE;

    public static void hire(long[] power, int[] money, int pos, int monster, int curM, long curP, boolean hire){
        if(pos == monster){
            if(curM < minM) minM = curM;
            return;
        }
        if(hire){
            curP += power[pos];
            curM += money[pos];
        }else if(curP < power[pos]){
            return;
        }
        hire(power, money, pos+1, monster, curM, curP, true);
        hire(power, money, pos+1, monster, curM, curP, false);
    }
}

猜你喜欢

转载自blog.csdn.net/LXQ1071717521/article/details/89076257