暴力:
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> #define maxn 100005 using namespace std; int main() { int a[maxn]; int n,k; int cas; int ans; cin >> cas; while(cas --){ cin >> n >> k; ans = n; for(int i = 0;i < n;i ++){ cin >> a[i]; } for(int i = 0;i < n;i ++){ int mmax = a[i]; int mmin = a[i]; for(int j = i+1;j < n;j ++){ if(a[j] < mmin) mmin = a[j]; if(a[j] > mmax) mmax = a[j]; if(mmax - mmin >= k) break; ans ++; } } cout << ans << endl; } return 0; }
ST算法: