http://codeforces.com/contest/710/problem/Dios
You are given two arithmetic progressions: a1k + b1 and a2l + b2. Find the number of integers x such that L ≤ x ≤ R and x = a1k' + b1 = a2l' + b2, for some integers k', l' ≥ 0.
spa
The only line contains six integers a1, b1, a2, b2, L, R (0 < a1, a2 ≤ 2·109, - 2·109 ≤ b1, b2, L, R ≤ 2·109, L ≤ R).
code
Print the desired number of integers x.
ip
2 0 3 3 5 21 2 4 3 0 6 17
3 2
求[L,R]區間內有多少個整數y知足 y = k1x1+b1 且 y = k2x2+b2. (x1 x2 >= 0)
ci
首先把兩條直線畫到平面上,題目限制了直線斜率都大於零. 又因爲 x1 x2 >= 0.
因此y的區間能夠進一步限制爲 [max(L, max(b1,b2)), R];
問題就變爲在這個新區間裏找使得兩個式子相等的"整點"個數了.
這裏能夠把兩個式子經過拓展中國剩餘定理(由於不互質)合併成一個式子, 而後計算區間內的解的個數便可.
注意:可能兩式子不能合併,直接輸出0; 正確計算區間內的解的個數(見註釋).
比賽作的時候只想到了拓展中國剩餘定理這裏,而後想的是b不必定小於k因此不算是模方程,覺得不能作.
實際上(拓展)中國剩餘定理在處理同餘模方程組的時候不要求餘數小於模數.
get
#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <queue> #include <map> #include <set> #include <stack> #include <vector> #include <list> #define LL long long #define eps 1e-8 #define maxn 10000100 #define mod 100000007 #define inf 0x3f3f3f3f3f3f3f3f #define mid(a,b) ((a+b)>>1) #define IN freopen("in.txt","r",stdin); using namespace std; LL x,y,gcd; void ex_gcd(LL a,LL b) { if(!b) {x=1;y=0;gcd=a;} else {ex_gcd(b,a%b);LL temp=x;x=y;y=temp-a/b*y;} } LL n,m[2],a[2]; //x%m=a LL cur, T; /*模線性方程組--不互質中國剩餘定理*/ int ex_China() { LL m1,m2,n1,n2,x0; m1=m[0];n1=a[0]; for(int i=1; i<n; i++) { m2=m[i]; n2=a[i]; ex_gcd(m1,m2); if((n2-n1)%gcd) return -1; LL tmp=m2/gcd; x0=(x*((n2-n1)/gcd)%tmp+tmp)%tmp; n1=n1+x0*m1; m1=m1/gcd*m2; } n1=(n1+m1)%m1; cur = n1; T = m1; return T; } int main(int argc, char const *argv[]) { //IN; n = 2; cin >> m[0] >> a[0] >> m[1] >> a[1]; LL L,R; cin >> L >> R; L = max(max(a[0], a[1]), L); int ret = ex_China(); LL ans = 0; if(ret == -1) { /*特判不能合併的方程組*/ printf("0\n"); return 0; } if(cur >= L) { /*找一個合適的起點,分別計算L-1和R到這個點之間有多少個解*/ cur -= ((cur-L)/T + 1) * T; } if(L <= R) { ans = (R - cur) / T - (L - 1 - cur) / T; } printf("%I64d\n", ans); return 0; }