文章
454
粉丝
0
获赞
1
访问
9.7k
用不超过 n 元买 100 只鸡:大鸡 5 元、小鸡 3 元、还有一种 1/3 元每只,枚举三种鸡的只数 (x,y,z) 的所有可行解。
枚举 x(大鸡)、y(小鸡),则 z = 100-x-y,花费 = 5x + 3y + z/3,判断 ≤ n 即可。
为避免浮点误差,把不等式两边乘 3:15x + 9y + z ≤ 3n。
按 x、y 从小到大枚举输出,格式 x=...,y=...,z=...;z 不能为负。
多组 n,逐组输出。
时间 O(n²)(实际 x、y 最多 100),空间 O(1)。
C:
#include <stdio.h>
int main(void){long long n;
while(scanf("%lld",&n)==1){
long long x,y,z;
for(x=0;x<=100;x++)for(y=0;y<=100-x;y++){
z=100-x-y;
if(15*x+9*y+z<=3*n)printf("x=%lld,y=%lld,z=%lld\n",x,y,z);}}
return 0;}
C++:
#include <iostream>
using namespace std;
int main(){long long n;
while(cin>>n){
for(long long x=0;x<=100;x++)for(long long y=0;y<=100-x;y++){
long long z=100-x-y;
if(15*x+9*y+z<=3*n)cout<<"x="<<x<<",y="<<y<<",z="<<z<<"\n";}}
return 0;}
Java:
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] z) throws IOException{
BufferedReader br=new BufferedReader(new Inp...
登录后发布评论
暂无评论,来抢沙发