#include<iostream> #include<algorithm> usingnamespace std; #define int long long voidsolve() { int n, k; cin >> n >> k; int tot = (k + n + k - 1) * n / 2; int l = k, r = k + n - 1, mid; while (l + 1 != r) { mid = l + r >> 1; int tot1 = (k + mid) * (mid - k + 1) / 2; if (tot1 < tot - tot1) l = mid; else r = mid; } int ltot = (k + l) * (l - k + 1) / 2; int ans = abs(tot - ltot - ltot); if (r < n + k - 1) ans = min(ans, abs(tot - ltot - r - ltot - r)); cout << ans << '\n'; } signedmain() { int t; cin >> t; while (t--) { solve(); } return0; }
#include<iostream> #define int long long usingnamespace std; constint N = 2e5 + 10; int a[N]; voidsolve() { int n, q; cin >> n >> q; for (int i = 1; i <= n; i++) cin >> a[i], a[i] += a[i - 1]; while (q--) { int lt = 0, rt = 0; int l, r; cin >> l >> r; //计算1 ~l-1 l = l - 1; lt += l / n * a[n]; if (l % n) { int le = (l / n + l % n) % n == 0 ? n : (l / n + l % n) % n;//映射到1-n int ls = 1; if (l / n) ls = ((l / n * n + 1) / n + (l / n * n + 1) % n) % n == 0 ? n : ((l / n * n + 1) / n + (l / n * n + 1) % n) % n; if (le >= ls) lt += a[le] - a[ls - 1]; else lt += a[n] - a[ls - 1] + a[le]; } //计算1 ~ r rt += r / n * a[n]; if (r % n) { int re = (r / n + r % n) % n == 0 ? n : (r / n + r % n) % n; int rs = 1; if(r / n) rs = ((r / n * n + 1) / n + (r / n * n + 1) % n) % n == 0 ? n : ((r / n * n + 1) / n + (r / n * n + 1) % n) % n; if (re >= rs) rt += a[re] - a[rs - 1]; else rt += a[n] - a[rs - 1] + a[re]; } cout << rt - lt << '\n'; } } signedmain() { int t; cin >> t; while (t--) { solve(); } return0; }
#include<iostream> #include<algorithm> #include<map> #include<set> usingnamespace std; #define int long long constint N = 1e5 + 10; int w[N], ans[N]; voidsolve() { int n, k, q; cin >> n >> k >> q; for (int i = 1; i <= n; i++) cin >> w[i], w[i] -= i; map<int, int> m;//存储一个数到它个数的映射 multiset<int> s;//用来存储各个数的数量,使用multiset可以直接排好序 for (int i = 1; i < k; i++) { if (m.find(w[i]) != m.end())//如果m中存在,就先把旧的数量删除,再存储进新的数量 s.erase(s.find(m[w[i]]));//删除pos m[w[i]]++; s.insert(m[w[i]]);//存储进新的数量 } for (int l = 1, r = k; l <= n; l++, r++) { if (r <= n) { if (m.find(w[r]) != m.end()) s.erase(s.find(m[w[r]])); m[w[r]]++; s.insert(m[w[r]]); } ans[l] = k - *s.rbegin();//因为是升序,找最大值用逆向迭代器 s.erase(s.find(m[w[l]])); m[w[l]]--; if (m[w[l]] == 0) m.erase(w[l]); else s.insert(m[w[l]]); } while (q--) { int l, r; cin >> l >> r; cout << ans[l] << '\n'; } } signedmain() { int t; cin >> t; while (t--) { solve(); } return0; }