codeforces 169 div2 C

http://codeforces.com/problemset/problem/276/C

比赛的时候用的线段树。裸的吧。还wa了3次。。

 1 //lazy_tag
 2 //区间求和操作
 3 #include <iostream>
 4 #include <cstdio>
 5 #include <cstring>
 6 #include <cmath>
 7 #include <algorithm>
 8 using namespace std;
 9 
10 #define lson l,m,rt<<1
11 #define rson m+1,r,rt<<1|1
12 #define MAXN 200010
13 int add[MAXN<<2];
14 long long  a[MAXN];
15 long long ans[MAXN];
16 void PushDown(int rt,int m)//m是父亲区间长度
17 {
18     if(add[rt])
19     {
20         add[rt<<1]+=add[rt];
21         add[rt<<1|1]+=add[rt];
22         add[rt]=0;
23     }
24 }
25 
26 //update
27 void update(int L,int R,int c,int l,int r,int rt)
28 {
29     if (L<= l && r<=R)    //节点区间[l,r]被目标区间[L,R]包含
30     {
31         add[rt]+=c;
32         if(L==R && c==0)
33         {
34             ans[L]+=add[rt];
35             add[rt]=0;
36         }
37         return ;
38     }
39     PushDown(rt,r-l+1);
40     int m = (l+r)>>1;
41     if(L<=m)
42         update(L,R,c,lson);
43     if(m<R)
44         update(L,R,c,rson);
45 }
46 
47 int main()
48 {
49     int N,Q;
50     while(scanf("%d%d",&N,&Q)!=EOF)
51     {
52         memset(ans,0,sizeof(ans));
53         memset(add,0,sizeof(add));
54         for(int i=0;i<N;i++)
55             scanf("%d",&a[i]);
56         sort(a,a+N);
57         while(Q--)
58         {
59             int l,r;
60             scanf("%d%d",&l,&r);
61             update(l,r,1,1,N,1);
62         }
63         for(int i=1;i<=N;i++)
64             update(i,i,0,1,N,1);
65         sort(ans+1,ans+N+1);
66         long long sum=0;
67         for(int i=0;i<N;i++)
68             sum+=ans[i+1]*a[i];
69         printf("%I64d\n",sum);
70     }
71     return 0;
72 }

不过看了别人的程序,觉得下面这种解法值得学习。ac了。以前好像看见过类似的问题,总是不知道怎么解决。作个保留。

 1 // File Name: cc.cpp
 2 // Author: Missa
 3 // Created Time: 2013/2/25 星期一 23:13:05
 4 
 5 #include<iostream>
 6 #include<cstdio>
 7 #include<cstring>
 8 #include<algorithm>
 9 #include<cmath>
10 #include<queue>
11 #include<stack>
12 #include<string>
13 #include<vector>
14 #include<cstdlib>
15 #include<map>
16 #include<set>
17 using namespace std;
18 #define CL(x,v) memset(x,v,sizeof(x));
19 #define R(i,st,en) for(int i=st;i<en;i++)
20 #define ll long long
21 const int maxn = 2e5+5;
22 ll a[maxn],ans[maxn],w[maxn];
23 int n,m;
24 
25 int main()
26 {
27     while(~scanf("%d%d",&n,&m))
28     {
29         CL(a,0);CL(ans,0);CL(w,0);
30         R(i,1,n+1)
31             scanf("%I64d",&a[i]);
32         R(i,0,m)
33         {
34             int l,r;
35             scanf("%d%d",&l,&r);
36             w[l]++;
37             w[r+1]--;
38         }
39         int tmp=0;
40         R(i,1,n+1)
41         {
42             tmp+=w[i];
43             ans[i]=tmp;
44         }
45         sort(ans+1,ans+n+1);
46         sort(a+1,a+n+1);
47         ll sum=0;
48         R(i,1,n+1)
49             sum+=a[i]*ans[i];
50         printf("%I64d\n",sum);
51     }
52     return 0;
53 }

 

posted @ 2013-02-25 23:26  Missa  阅读(232)  评论(0编辑  收藏  举报