Esempio n. 1
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var  n       = inputStream.ReadInt();
            var  p       = inputStream.ReadIntArray();
            var  indices = new int[n];
            long sum     = 0;

            for (int i = 0; i < p.Length; i++)
            {
                indices[p[i] - 1] = i + 1;
            }

            var bit = new BinaryIndexedTree(n + 2);

            bit[0]     += 2;
            bit[n + 1] += 2;

            for (int pi = n; pi > 0; pi--)
            {
                var index = indices[pi - 1];

                var left  = bit.Sum(..index);
                var right = bit.Sum((index + 1)..);

                var left2  = bit.GetLowerBound(left - 1) + 1;
                var left1  = bit.GetLowerBound(left) + 1;
                var right1 = bit.GetLowerBound(left + 1);
                var right2 = bit.GetLowerBound(left + 2);

                sum += (long)(left1 - left2) * (right1 - index) * pi;
                sum += (long)(index - left1 + 1) * (right2 - right1) * pi;
                bit[index]++;
            }

            yield return(sum);
        }
Esempio n. 2
0
        public override IEnumerable <object> Solve(TextReader inputStream)
        {
            var bit     = new BinaryIndexedTree(2000001);
            var queries = inputStream.ReadInt();

            for (int q = 0; q < queries; q++)
            {
                var(type, x) = inputStream.ReadValue <int, int>();
                if (type == 1)
                {
                    bit[x]++;
                }
                else
                {
                    var index = bit.GetLowerBound(x);
                    bit[index]--;
                    yield return(index);
                }
            }
        }