差分简单题集 POJ 2155 Matrix (二维树状数组+差分)

【一维差分】Codeforces 1000C Covered Points Count 

题目大意:

给定$n$个线段,给定这些线段所在的区间($l,r\leq10^{18}$),这些线段能够覆盖它们所包含的点,问你被包含$[1,n]$次的点分别有多少个。

解题分析:
用差分来高效的统计一下指定区间内所被覆盖的线段个数,同时,因为$l,r$的大小非常大,所以我们需要对所有的线段进行离散化。

#include <bits/stdc++.h>
using namespace std;
template<typename T>
inline void read(T&x){        
    x=0;int f=1;char ch=getchar();
    while(ch<'0' ||ch>'9'){ if(ch=='-')f=-1; ch=getchar(); }
    while(ch>='0' && ch<='9'){ x=x*10+ch-'0'; ch=getchar(); }
    x*=f;
}
#define REP(i,s,t) for(int i=s;i<=t;i++)
typedef long long ll;
map<ll,ll>mp;
int main(){
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    int n;cin>>n;
    REP(i,1,n){
        ll l,r;read(l);read(r);
        mp[l]++,mp[r+1]--;
    }
    vector<ll>ans(n+10);
    ll last=0,sum=0;    //last统计上一个区间端点的下标,sum计算前缀和
    for(auto e:mp){
        ans[sum]+=(e.first-last);      
        sum+=e.second;
        last=e.first;
    }
    REP(i,1,n)cout<<ans[i]<<" ";
}
View Code

【一维差分】Codeforces 853B Jury Meeting (差分+前缀和)

【二维差分】POJ 2155 Matrix (二维树状数组+差分)

【树上差分】CodeForces 739B Alyona and a tree (二分+树上差分)

猜你喜欢

转载自www.cnblogs.com/00isok/p/10927070.html