Color the ball
題意:
給定一個整數 n ,表示有 n 個氣球,從 1~n 編號,接下來 n 行,每行有兩個整數 a、b,表示從氣球 a 到氣球 b 給每個氣球塗一次顏色,求最後每個氣球被塗過幾次顏色。
數據範圍:
n <= 100000,1 <= a <= b <= n
解題思路:
樹狀數組 差分 or 差分前綴和
剛學樹狀數組來做這題的時候,突然發現我以前做過,那個時候是直接用差分
的思想來做的,處理完 n 次操作以後計算一下差分的前綴和
就是答案了,實現起來挺簡單的;後來又用樹狀數組重新做了一遍,熟悉樹狀數組的模板以後寫起來也快也簡單,而且跑得還稍微快一些。
代碼:
① 差分前綴和:
Exe.Time : 873MS | Exe.Memory : 2192KB
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define MAX 100005
int sum[MAX]={0};
int main()
{
int n,a,b;
while(scanf("%d",&n)!=EOF,n)
{
memset(sum,0,sizeof(sum));
for(int i=1;i<=n;i++){
scanf("%d%d",&a,&b);
sum[a]++;
sum[b+1]--;
}
for(int i=1;i<=n;i++){
sum[i]+=sum[i-1];
cout<<sum[i];
if(i<n) cout<<" ";
}
cout<<endl;
}
return 0;
}
① 樹狀數組 差分:
Exe.Time : 764MS | Exe.Memory : 2140KB
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
using namespace std;
#define INF 0x3f3f3f
#define zero 1e-7
typedef long long ll;
const int N=1e5+5;
int sum[N], n;
int lowbit(int x) {
return x&(-x);
}
void add(int x, int c) {
while(x<=n) {
sum[x]+=c;
x+=lowbit(x);
}
return ;
}
int query(int x) {
int ans=0;
while(x) {
ans+=sum[x];
x-=lowbit(x);
}
return ans;
}
int main() {
int a, b;
while(scanf("%d", &n), n) {
memset(sum, 0, sizeof(sum));
for(int i=1; i<=n; i++) {
scanf("%d %d", &a, &b);
add(a, 1);
add(b+1, -1);
}
for(int i=1; i<=n; i++) {
printf("%d", query(i));
if(i<n) printf(" ");
}
printf("\n");
}
return 0;
}