【Foreign】不等式 [数论]

不等式

Time Limit: 10 Sec  Memory Limit: 128 MB

Description

  小z热衷于数学。
  今天数学课的内容是解不等式:L<=S*x<=R 。小z心想这也太简单了,不禁陷入了深深的思考:假如已知L,R,S,M ,满足L<=(S*x) mod M<=R 的最小正整数x该怎么求呢?

Input

  第一行包含一个整数T,表示数据组数,接下来是T行,每行为四个正整数M, S, L, R 。

Output

  对于每组数据,输出满足要求的x值,若不存在,输出-1 。

Sample Input

  1
  5 4 2 3

Sample Output

  2

HINT

  30%的数据中保证有解并且答案小于等于10^6;
  另外20%的数据中保证L=R;
  100%的数据中T<=100,M, S, L, R<=10^9。

Solution

  闷声放题解qwq。

  

Code

 1 #include<iostream>    
 2 #include<string>    
 3 #include<algorithm>    
 4 #include<cstdio>    
 5 #include<cstring>    
 6 #include<cstdlib>
 7 #include<cmath>
 8 #include<bitset>
 9 using namespace std;  
10 typedef long long s64;
11 
12 const int ONE = 300005;
13 const int MOD = 1e9 + 7;
14 
15 int T;
16 s64 M, S, L, R; 
17 
18 int get()
19 {    
20         int res=1,Q=1;char c;    
21         while( (c=getchar())<48 || c>57 ) 
22         if(c=='-')Q=-1; 
23         res=c-48;     
24         while( (c=getchar())>=48 && c<=57 )    
25         res=res*10+c-48;    
26         return res*Q;
27 }
28 
29 s64 Dfs(s64 M, s64 S, s64 L, s64 R)
30 {
31         if(L > R || M < L) return -1;
32         
33         S %= M;
34         int res = (L - 1)/S + 1;
35         if(res * S <= R) return res;
36         
37         int l = (-R % S + S) % S,  r = (-L % S + S) % S;
38         int y = Dfs(S, M, l , r); if(y == -1) return -1;
39         
40         int x = (R + M * y) / S;
41         if(L <= S * x - M * y) return x;
42         return -1;
43 }
44 
45 int main()
46 {
47         T = get();
48         while(T--)
49         {
50             M = get();    S = get();
51             L = get();    R = get();
52             
53             printf("%d\n", Dfs(M, S, L, min(R, M-1)));
54         }
55         
56 }
View Code

 

posted @ 2017-06-24 16:36  BearChild  阅读(621)  评论(0编辑  收藏  举报