牛客对应题目链接:ruby和薯条 (nowcoder.com)
先排序,然后枚举较⼤值,在 [1, i - 1] 区间找差值的左右端点即可。
// 修改过后的代码 #include #include using namespace std; typedef long long LL; int n, l, r; const int N=2e5+10; int a[N]; LL s(int x) { LL res=0; int left=0, right=0; while(rightx) left++; res+=right-left; right++; } return res; } int main() { cin >> n >> l >> r; for(int i=0; i> a[i]; sort(a, a+n); cout << s(r)-s(l-1) << endl; return 0; }
// 推荐解法一:排序 + 前缀和 + 滑动窗⼝ #include #include using namespace std; const int N = 2e5 + 10; int n, l, r; int arr[N]; // 找出差值在 [0, x] 之间⼀共有多少对 long long find(int x) { int left = 0, right = 0; long long ret = 0; while(right < n) { while(arr[right] - arr[left] > x) left++; ret += right - left; right++; } return ret; } int main() { cin >> n >> l >> r; for(int i = 0; i < n; i++) cin >> arr[i]; sort(arr, arr + n); cout << find(r) - find(l - 1) << endl; return 0; } //解法二:排序 + ⼆分 #include #include using namespace std; const int N = 2e5 + 10; int n, l, r; int arr[N]; int main() { cin >> n >> l >> r; for(int i = 1; i <= n; i++) cin >> arr[i]; sort(arr + 1, arr + n + 1); long long ret = 0; for(int i = 2; i <= n; i++) { int L, R; // 找左端点 int left = 1, right = i - 1; while(left < right) { int mid = (left + right) / 2; if(arr[mid] >= arr[i] - r) right = mid; else left = mid + 1; } if(arr[left] >= arr[i] - r) L = left; else L = left + 1; // 找右端点 left = 1, right = i - 1; while(left < right) { int mid = (left + right + 1) / 2; if(arr[mid] <= arr[i] - l) left = mid; else right = mid - 1; } if(arr[left] <= arr[i] - l) R = left; else R = left - 1; if(R >= L) ret += R - L + 1; } cout << ret << endl; return 0; }
双指针部分思路繁琐了,还有就是求前缀和的函数返回值的类型忘记修改为 long long 了...