题目:http://acm.hdu.edu.cn/showproblem.php?pid=1573
思路:同余方程,模板
#include <cstdio> #include <iostream> #include <cmath> #include <algorithm> #include <cstring> using namespace std; long long a[11],b[11]; long long exgcd(long long a,long long b,long long &x,long long &y) { if(b==0) { x=1; y=0; return a; } else { long long ans=exgcd(b,a%b,x,y); long long t=x; x=y; y=t-a/b*y; return ans; } } long long gcd(long long a,long long b) { if(b==0) return a; return gcd(b,a%b); } long long lcm(long long a,long long b) { return a/gcd(a,b)*b; } bool solve(int n) { a[0]=a[1],b[0]=b[1]; for(int i=2;i<=n;i++) { long long a0=b[0]; long long b0=b[i]; long long c0=a[i]-a[0]; long long x0,y0; long long r=gcd(a0,b0); if(c0%r!=0) return false; else { a0/=r; b0/=r; c0/=r; exgcd(a0,b0,x0,y0); x0*=c0; x0=(x0%b0+b0)%b0; a[0]=b[0]*x0+a[0]; b[0]=b[0]*b0; } } return true; // a[0]为小于[b1,b2...bn]的非负整数解 } int main() { int t; cin>>t; while(t--) { long long n,m; cin>>n>>m; long long tmp=1; for(int i=1;i<=m;i++) { cin>>b[i]; tmp=lcm(tmp,b[i]); } for(int i=1;i<=m;i++) cin>>a[i]; long long ans=0; long long cnt; if(solve(m)) { cnt=a[0]; if(cnt<n) { ans=1+(n-cnt)/tmp; } if(cnt==0) ans--;//0不是正整数 } cout<<ans<<endl; } return 0; }