#include <cstdio> #include <algorithm> using namespace std; typedef long long int lld; int d[50]; int n; lld f(int a, int b) { if(a==0 || b==0)return 0; if(a>b)swap(a,b); for(int i=n-1;i>=0;i--) { if(d[i]<=a) { lld x=f(a%d[i],b-b%d[i]); if(x==-1)return -1; lld y=f(a,b%d[i]); if(y==-1)return -1; return lld(a/d[i])*lld(b/d[i])+x+y; } } return -1; } int main() { int a,b; scanf("%d %d",&a,&b); scanf("%d",&n); for(int i=0;i<n;i++)scanf("%d",&d[i]); printf("%lld\n",f(a,b)); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | #include <cstdio> #include <algorithm> using namespace std; typedef long long int lld; int d[50]; int n; lld f(int a, int b) { if(a==0 || b==0)return 0; if(a>b)swap(a,b); for(int i=n-1;i>=0;i--) { if(d[i]<=a) { lld x=f(a%d[i],b-b%d[i]); if(x==-1)return -1; lld y=f(a,b%d[i]); if(y==-1)return -1; return lld(a/d[i])*lld(b/d[i])+x+y; } } return -1; } int main() { int a,b; scanf("%d %d",&a,&b); scanf("%d",&n); for(int i=0;i<n;i++)scanf("%d",&d[i]); printf("%lld\n",f(a,b)); } |