include iostream include iomanip include cstdio include string include

 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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef ld DOUBLE;
#define PATH "D:\\QtProjects\\olymp\\"
template <class T> void mx(T& a, const T& b) { if (a < b) a = b; }
template <class T> void mn(T& a, const T& b) { if (a > b) a = b; }
int main(){
// freopen(PATH"input.txt", "r", stdin);
ios_base::sync_with_stdio(false);
int t;
cin >> t;
for (int i = 0; i < t; ++i){
ll x, y, k, t;
cin >> x >> y >> k >> t;
if (x % y == 0){
ll ans = x + y * min(k, t);
if (t > k) ans += t - k;
cout << ans << endl;
}
else{
ll w1 = (x / y + 1) * y;
w1 += y * min(k - 1, t);
if (t > k - 1) w1 += t - k + 1;
ll d = y - x % y;
if (d == y) d = 0;
ll w2 = x + d;
t -= d;
if (t < 0) w2 = -1;
else {
w2 += y * min(k, t);
if (t > k) w2 += t - k;
}
cout << max(w1, w2) << endl;
}
}
return 0;
}