zoukankan      html  css  js  c++  java
  • HDU 1556.Color the ball-差分数组-备忘

    备忘。

    差分数组:

    区间更新查询有很多方法,线段树、树状数组等都可以。如果为离线查询,就可以考虑使用差分数组。

    假设对于区间[l,r]的每个数都加1,我们用一个数组a来记录,a[l]+=1;a[r+1]-=1;

    然后使用一个数组ans来记录数组a的前缀和,ans[i]=ans[i-1]+a[i];ans保存的就是所有更新操作完成后每个数对应的值。

    原理很好理解,树状数组也有这种思想。

    差分数组代码可比线段树短了相当多,记住这个还是很好的。

    Color the ball

    Time Limit: 9000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
    Total Submission(s): 29031    Accepted Submission(s): 14125


    Problem Description
    N个气球排成一排,从左到右依次编号为1,2,3....N.每次给定2个整数a b(a <= b),lele便为骑上他的“小飞鸽"牌电动车从气球a开始到气球b依次给每个气球涂一次颜色。但是N次以后lele已经忘记了第I个气球已经涂过几次颜色了,你能帮他算出每个气球被涂过几次颜色吗?
     
    Input
    每个测试实例第一行为一个整数N,(N <= 100000).接下来的N行,每行包括2个整数a b(1 <= a <= b <= N)。
    当N = 0,输入结束。
     
    Output
    每个测试实例输出一行,包括N个整数,第I个数代表第I个气球总共被涂色的次数。
     
    Sample Input
    3
    1 1
    2 2
    3 3
    3
    1 1
    1 2
    1 3
    0
     
    Sample Output
    1 1 1
    3 2 1
     
    Author
    8600
     
    Source
     

    题意很好理解,就是区间更新然后查询,是离线操作,差分数组登场,bling~bling~

    代码:

     1 //HDU 1556-差分数组 备忘
     2 #include<iostream>
     3 #include<cstdio>
     4 #include<cstring>
     5 #include<algorithm>
     6 #include<bitset>
     7 #include<cassert>
     8 #include<cctype>
     9 #include<cmath>
    10 #include<cstdlib>
    11 #include<ctime>
    12 #include<deque>
    13 #include<iomanip>
    14 #include<list>
    15 #include<map>
    16 #include<queue>
    17 #include<set>
    18 #include<stack>
    19 #include<vector>
    20 using namespace std;
    21 typedef long long ll;
    22 
    23 const double PI=acos(-1.0);
    24 const double eps=1e-6;
    25 const ll mod=1e9+7;
    26 const int inf=0x3f3f3f3f;
    27 const int maxn=1e5+10;
    28 const int maxm=100+10;
    29 #define ios ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
    30 #define lson l,m,rt<<1
    31 #define rson m+1,r,rt<<1|1
    32 
    33 int a[maxn],ans[maxn];
    34 
    35 int main()
    36 {
    37     int n;
    38     while(scanf("%d",&n)){
    39         if(n==0) break;
    40         memset(a,0,sizeof(a));
    41         memset(ans,0,sizeof(ans));
    42         for(int i=0;i<n;i++){
    43             int l,r;
    44             scanf("%d%d",&l,&r);
    45             a[l]+=1;
    46             a[r+1]-=1;
    47         }
    48         ans[0]=0;
    49         for(int i=1;i<=n;i++){
    50                 ans[i]=ans[i-1]+a[i];
    51         }
    52         for(int i=1;i<n;i++)
    53             printf("%d ",ans[i]);
    54             printf("%d
    ",ans[n]);
    55     }
    56 }
  • 相关阅读:
    Android Studio 活动启动模式
    Android Studio 活动的生命周期
    OA表单制作(致远)
    打开excel打印时报“不能使用对象链接和嵌入”
    C#面对对象之封装、继承、多态的简单理解
    C#上手练习7(构造方法语句)
    C#上手练习7(方法语句2)
    C#上手练习6(方法语句1)
    C#上手练习5(GOTO语句)
    C#上手练习4(Break、CONITINUE语句)
  • 原文地址:https://www.cnblogs.com/ZERO-/p/9762310.html
Copyright © 2011-2022 走看看