技巧(1)sum[end] - sum[start]
Flowers
Time Limit: 2000ms
Memory Limit: 65536KB
64-bit integer IO format: %I64d Java class name: MainAs is known to all, the blooming time and duration varies between different kinds of flowers. Now there is a garden planted full of flowers. The gardener wants to know how many flowers will bloom in the garden in a specific time. But there are too many flowers in the garden, so he wants you to help him.
Input
The first line contains a single integer t (1 <= t <= 10), the number of test cases.
For each case, the first line contains two integer N and M, where N (1 <= N <= 10^5) is the number of flowers, and M (1 <= M <= 10^5) is the query times.
In the next N lines, each line contains two integer Si and Ti (1 <= Si <= Ti <= 10^9), means i-th flower will be blooming at time [Si, Ti].
In the next M lines, each line contains an integer Ti, means the time of i-th query.
For each case, the first line contains two integer N and M, where N (1 <= N <= 10^5) is the number of flowers, and M (1 <= M <= 10^5) is the query times.
In the next N lines, each line contains two integer Si and Ti (1 <= Si <= Ti <= 10^9), means i-th flower will be blooming at time [Si, Ti].
In the next M lines, each line contains an integer Ti, means the time of i-th query.
Output
For each case, output the case number as shown and then print M lines. Each line contains an integer, meaning the number of blooming flowers.
Sample outputs are available for more details.
Sample outputs are available for more details.
Sample Input
2 1 1 5 10 4 2 3 1 4 4 8 1 4 6
Sample Output
Case #1: 0 Case #2: 1 2 1
#include<cstdio> #include<algorithm> using namespace std; int s[100005]; int e[100005]; int main(){ int T,cas = 0; scanf("%d",&T); while(T--){ int n,m; scanf("%d%d",&n,&m); for(int i = 0; i < n; i++){ scanf("%d%d",&s[i],&e[i]); } sort(s,s+n); sort(e,e+n); printf("Case #%d:\n",++cas); while(m--){ int ans = 0; int x; scanf("%d",&x); ans += upper_bound(s,s+n,x)-s;//在时间x前开的花的数目,因为是从0开始标记的,所以他的下标不是他本身,而是他前面所有的数量;是upper_bound. ans -= lower_bound(e,e+n,x)-e;//在时间x前凋谢的花的数目,注意在时间t凋谢,但时间t时花还是开着的。所以是lower_bound. printf("%d\n",ans); } } return 0; }
/*帮助理解的TLE代码*/
#include<cstdio> #include<algorithm> using namespace std; int s[100005]; int e[100005]; int main(){ int T,cas = 0; scanf("%d",&T); while(T--){ int n,m; scanf("%d%d",&n,&m); for(int i = 0; i < n; i++) scanf("%d%d",&s[i],&e[i]); sort(s,s+n); sort(e,e+n); while(m--){ int cnt,x,ans = 0; scanf("%d",&x); for(cnt = 0; cnt < n; cnt++) if(s[cnt] > x)break; ans += cnt; for(cnt = 0; cnt < n; cnt++) if(e[cnt] >= x)break; ans -= cnt; printf("%d\n",ans); } } return 0; }

浙公网安备 33010602011771号