Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10068 | Accepted: 4096 |
Description
Input
Output
2 10 15 5 1 3 5 10 7 4 9 2 8 5 11 1 2 3 4 5
Sample Output
2 3
Source
1.尺区法 #include<iostream> #include<cstdio> #include<algorithm> using namespace std; #define N 101000 #define inf 0x3f3f3f3f int a[N]; int main() { #ifdef CDZSC freopen("i.txt", "r",stdin); #endif int t, n, s; scanf("%d", &t); while (t--) { scanf("%d%d", &n, &s); for (int i = 1; i <= n; i++) scanf("%d", a + i); int l=1, r=1, ans = inf,sum=0; while (true) { while (sum < s&&r <= n) { sum += a[r++]; } if (sum < s)break; ans = min(ans, r - l); sum -= a[l++]; } printf("%d\n", ans == inf ? 0 : ans); } return 0; } 2.二分 #include<iostream> #include<cstdio> #include<algorithm> #include<cstring> using namespace std; #define N 101000 #define LL long long #define inf 0x3f3f3f3f int a[N]; LL sum[N]; int main() { #ifdef CDZSC freopen("i.txt", "r", stdin); #endif int n, t, s,ans; scanf("%d", &t); while (t--) { ans = inf; memset(sum, 0, sizeof(sum)); scanf("%d%d", &n, &s); for (int i = 1; i <= n; i++) scanf("%d", a + i); for (int i = 0; i < n; i++) sum[i + 1] = sum[i] + a[i+1]; if (sum[n] < s)ans = 0; for (int i = 1; sum[i] + s <= sum[n]; i++) { int w = lower_bound(sum + 1, sum + n, sum[i] + s) - sum; ans = min(ans, w - i); } printf("%d\n", ans); } return 0; }