Yandex.Algorithm 2011 Round 2 D. Powerful array 莫队算法

链接:

http://codeforces.com/problemset/problem/86/D

题意:

给你一个数组,每次询问一个区间,求对于每个数,算出这个数在这个区间出现的个数的平方再*这个数,全部加起来求和

题解:

时限5000ms,结果4898ms飘过,期间改了无数次一直超时,直到我把所有能把long long换成int的全部换了才过。。感觉这道题不适合用莫队算法过吧

代码:

31 int n, m;
32 int sz;
33 int a[MAXN];
34 ll ans[MAXN];
35 ll sum[MAXN];
36 
37 struct node {
38     int l, r, id;
39     bool operator<(const node &t) const {
40         if (l / sz == t.l / sz) return r < t.r;
41         return l < t.l;
42     }
43 }q[MAXN];
44 
45 int L = 1, R = 0;
46 ll Sum = 0;
47 
48 void update(int x, int add) {
49     Sum -= sum[a[x]] * sum[a[x]] * a[x];
50     sum[a[x]] += add;
51     Sum += sum[a[x]] * sum[a[x]] * a[x];
52 }
53 
54 int main() {
55     cin >> n >> m;
56     sz = sqrt(n);
57     rep(i, 1, n + 1) scanf("%d", a + i);
58     rep(i, 0, m) {
59         scanf("%d%d", &q[i].l, &q[i].r);
60         q[i].id = i;
61     }
62     sort(q, q + m);
63     rep(i, 0, m) {
64         while (L < q[i].l) update(L++, -1);
65         while (L > q[i].l) update(--L, 1);
66         while (R < q[i].r) update(++R, 1);
67         while (R > q[i].r) update(R--, -1);
68         ans[q[i].id] = Sum;
69     }
70     rep(i, 0, m) printf("%I64d\n", ans[i]);
71     return 0;
72 }

 

posted @ 2017-05-03 13:05  Flowersea  阅读(209)  评论(6编辑  收藏  举报