输入包括一行,四个整数x, f, d, p(1 ≤ x,f,d,p ≤ 2 * 10^9),以空格分割
输出一个整数, 表示小易最多能独立生活多少天。
3 5 100 10
11
import java.util.*; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner cin=new Scanner (System.in); long x=cin.nextInt();//一天的租金 long f=cin.nextInt();//手中已有的水果数 long d=cin.nextInt();//总的现金 long p=cin.nextInt();//一个水果的价格 long out=0; if(d/x>=f) { out=out+((d-f*x)/(x+p))+f; } else { out=d/x; } /* * for (int i =0;;i++) { if(d<x)break; else if(d>=x && (f<=0&&d<x+p))break; else { d=d-x; if(f>0)f--; else if(f<=0){ d=d-p; } out++; } } */ System.out.print(out); } }
import java.util.Scanner; public class Main{ public static Scanner scan=new Scanner(System.in); public static void main(String[] args) { int x=scan.nextInt(); int f=scan.nextInt(); int d=scan.nextInt(); int p=scan.nextInt(); //在水果吃完时交的房费 int Beformoney = f*x; //在水果吃完,交完的房费,剩下的钱 int aftermoney=d-Beformoney; // 如果还有剩余的钱 if(aftermoney>0) { //得出交完房费和水果钱的生活天数 int num = aftermoney/(x+p); if(num>=0) { System.out.println(num+f); }else { //剩下的钱不够一天的生活 System.out.println(f); } //钱透支了,在f个水果没吃完,钱已经不够交房租了 //求交了几天房费 }else if(aftermoney<0) { System.out.println(d/x); }else { //正好吃完水果,钱也够交房租 System.out.println(f); } } }
1.有水果就每天就交租房费,水果量减1。
2.没水果就同时交租房费和水果费。
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int x = sc.nextInt(); int f = sc.nextInt(); int d = sc.nextInt(); int p = sc.nextInt(); int total = 0; while (d >= 0) { if (f > 0) { d -= x; f--; } else { d -= (x + p); } if (d >= 0) { total++; } } System.out.println(total); } }
一开始使用的模拟,时间复杂度有点高:
private static int solution(int x, int f, int d, int p) { int res = 0; if (x > d) return res; while (f > 0 && d > 0) { d -= x; f--; res++; } if (d <= 0) return res; while (d > p + x) { d -= (p + x); res++; } return res; }
仔细考虑下,只有三种情况:
private static int solution(int x, int f, int d, int p) { if (x > d) return 0; // 带的钱交不起房租 if (d - (x * f) > 0) { // 在苹果吃完之后还有剩余的钱 int m = d - (x * f); return f + m / (p + x); } else { // 苹果没吃完之前就没钱了 return d / x; } }
import java.util.Scanner;public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); long house = sc.nextInt(); long firut = sc.nextInt(); long money = sc.nextInt();long cost = sc.nextInt();long nowMoney = firut*cost+money; long oneday = house + cost; if (nowMoney/oneday >= money/house){ System.out.println((int)Math.floor(money/house)); } else { System.out.println((int)Math.floor(nowMoney/oneday)); } } }