可以采用遍历一个变量
自己定一个遍历次数
x⋅w+y⋅d=p
x+y+z=n
#include <iostream>
#include <cstdio>
#define ll long long
using namespace std;
const int N=10*1000*1000;
int main(){
ll n,p,w,d;//比赛的场数,最后得分,赢了的得分,平局的得分
cin>>n>>p>>w>>d;
for(ll i=0;i<=N;i++){//遍历一次x
ll t = p-(w*i);//t = y*d
if(t>=0&&t%d==0 && i+(t/d)<=n){//z的大小不用管,因为z的多少只与x和y的多少有关,而且z的多少不会对总分数产生影响
cout<<i<<" "<<t/d<<" "<<n - i - (t / d)<<endl;
return 0;
}
}
for(int i=0;i<=N;i++){//遍历一次y,因为只遍历x,可能找不到答案,比如x特别大的时候
ll t=p-(d*i);
if(t>=0&&t%w==0 && i+(t/w)<=n){
cout<<t/w<<" "<<i<<" "<<n - i - (t / w)<<endl;
return 0;
}
}
cout<<-1;
return 0;
}
/*
已知w d p n
求解方程的x y z
x⋅w+y⋅d=p
x+y+z=n
这种求解方程的题,要不退出规律,要不就进行很大的暴力搜索
*/