結果

問題 No.1733 Sum of Sorted Subarrays
ユーザー cyclerecycle9cyclerecycle9
提出日時 2021-12-14 23:01:52
言語 Java21
(openjdk 21)
結果
AC  
実行時間 1,493 ms / 3,000 ms
コード長 17,200 bytes
コンパイル時間 3,251 ms
コンパイル使用メモリ 103,032 KB
実行使用メモリ 129,260 KB
最終ジャッジ日時 2023-10-01 02:13:57
合計ジャッジ時間 29,740 ms
ジャッジサーバーID
(参考情報)
judge14 / judge13
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 55 ms
48,228 KB
testcase_01 AC 55 ms
50,532 KB
testcase_02 AC 54 ms
50,112 KB
testcase_03 AC 54 ms
50,164 KB
testcase_04 AC 56 ms
50,036 KB
testcase_05 AC 57 ms
50,168 KB
testcase_06 AC 55 ms
50,212 KB
testcase_07 AC 55 ms
50,540 KB
testcase_08 AC 926 ms
94,672 KB
testcase_09 AC 1,231 ms
120,880 KB
testcase_10 AC 855 ms
90,616 KB
testcase_11 AC 1,008 ms
96,272 KB
testcase_12 AC 1,065 ms
115,256 KB
testcase_13 AC 1,072 ms
114,904 KB
testcase_14 AC 1,493 ms
127,020 KB
testcase_15 AC 1,368 ms
121,556 KB
testcase_16 AC 886 ms
90,520 KB
testcase_17 AC 1,462 ms
128,484 KB
testcase_18 AC 1,208 ms
116,080 KB
testcase_19 AC 1,224 ms
118,816 KB
testcase_20 AC 1,161 ms
115,088 KB
testcase_21 AC 1,309 ms
120,664 KB
testcase_22 AC 1,040 ms
96,808 KB
testcase_23 AC 1,482 ms
128,156 KB
testcase_24 AC 1,452 ms
129,024 KB
testcase_25 AC 1,473 ms
129,260 KB
testcase_26 AC 732 ms
111,348 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock;
import java.beans.Visibility;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UncheckedIOException;
import java.lang.Thread.State;
import java.lang.reflect.Field;
import java.nio.CharBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;

public class Main {
	static final long MOD1=1000000007;
	static final long MOD=998244353;
	static long ans=0;
	static long[] two;
	public static void main(String[] args){
		PrintWriter out = new PrintWriter(System.out);
		InputReader sc=new InputReader(System.in);
		int n = sc.nextInt();
		long[] A = sc.nextLongArray(n);
		ArrayList<Pair> list = new ArrayList<>();
		for (int i = 0; i < A.length; i++) {
			list.add(new Pair(A[i], i));
		}
		Collections.sort(list);
		two = any_mod_pow(2l, n, MOD);
		S[] dat = new S[n];
		S2[] dat2 = new S2[n];
		Arrays.fill(dat, new S(1l, 0));
		Arrays.fill(dat2, new S2(1l, 0));
		SegTree<S> seg1 = new SegTree<S>(dat, S::op, S.E);
		SegTree<S2> seg2 = new SegTree<S2>(dat2, S2::op, S2.E);
		long ans = 0;
		for (Pair p: list){
			long l = seg2.prod(0, p.y+1).sum;
			long r = seg1.prod(p.y, n).sum;
			ans = (ans + (((l*r)%MOD)*p.x)%MOD)%MOD;
			seg1.set(p.y, new S(2l, 1));
			seg2.set(p.y, new S2(2l, 1));
		}
		System.out.println(ans);
   	}
	static class Pair implements Comparable<Pair>{
    	public long x;
    	public int y;
    	public Pair(long x,int y) {
    		this.x=x;
    		this.y=y;
    	}
    	@Override
    	public boolean equals(Object obj) {
    		if(obj instanceof Pair) {
    			Pair other = (Pair) obj;
    			return other.x==this.x && other.y==this.y;
    		}
    		return false;
    	}//同値の定義
    	@Override
    	public int hashCode() {
    		return Objects.hash(this.x,this.y);
    	}//これ書かないと正しく動作しない(要 勉強)
    	@Override
    	public int compareTo( Pair p){
    		if (this.x>p.x) {
    			return 1;
    		}
    		else if (this.x<p.x) {
    			return -1;
    		}
    		else {
    			return 0;
    		}
    	}
    }
	static long[] any_mod_pow(long a,int size,long MOD){
    	long[] pow = new long[size+1];
    	pow[0] = 1l;
    	for (int i = 1; i < pow.length; i++) {
			pow[i] = (pow[i-1]*a)%MOD;
		}
    	return pow;
    }
	static class S{
		long sum;
		int two_sum;
		static S E = new S(0, 0);
		public S(long sum,int two_sum) {
			this.sum = sum;
			this.two_sum = two_sum;
		}
		static S op(S a,S b) {
			return new S((a.sum+(b.sum*two[a.two_sum])%MOD)%MOD, a.two_sum+b.two_sum);
		}
	}
	static class S2{
		long sum;
		int two_sum;
		static S2 E = new S2(0, 0);
		public S2(long sum,int two_sum) {
			this.sum = sum;
			this.two_sum = two_sum;
		}
		static S2 op(S2 a,S2 b) {
			return new S2((b.sum+(a.sum*two[b.two_sum])%MOD)%MOD, a.two_sum+b.two_sum);
		}
	}
	static class SegTree<S> {
		    final int MAX;

		    final int N;
		    final java.util.function.BinaryOperator<S> op;
		    final S E;

		    final S[] data;

		    @SuppressWarnings("unchecked")
		    public SegTree(int n, java.util.function.BinaryOperator<S> op, S e) {
		        this.MAX = n;
		        int k = 1;
		        while (k < n) k <<= 1;
		        this.N = k;
		        this.E = e;
		        this.op = op;
		        this.data = (S[]) new Object[N << 1];
		        java.util.Arrays.fill(data, E);
		    }

		    public SegTree(S[] dat, java.util.function.BinaryOperator<S> op, S e) {
		        this(dat.length, op, e);
		        build(dat);
		    }

		    private void build(S[] dat) {
		        int l = dat.length;
		        System.arraycopy(dat, 0, data, N, l);
		        for (int i = N - 1; i > 0; i--) {
		            data[i] = op.apply(data[i << 1 | 0], data[i << 1 | 1]);
		        }
		    }

		    public void set(int p, S x) {
		        exclusiveRangeCheck(p);
		        data[p += N] = x;
		        p >>= 1;
		        while (p > 0) {
		            data[p] = op.apply(data[p << 1 | 0], data[p << 1 | 1]);
		            p >>= 1;
		        }
		    }

		    public S get(int p) {
		        exclusiveRangeCheck(p);
		        return data[p + N];
		    }

		    public S prod(int l, int r) {
		        if (l > r) {
		            throw new IllegalArgumentException(
		                String.format("Invalid range: [%d, %d)", l, r)
		            );
		        }
		        inclusiveRangeCheck(l);
		        inclusiveRangeCheck(r);
		        S sumLeft = E;
		        S sumRight = E;
		        l += N; r += N;
		        while (l < r) {
		            if ((l & 1) == 1) sumLeft = op.apply(sumLeft, data[l++]);
		            if ((r & 1) == 1) sumRight = op.apply(data[--r], sumRight);
		            l >>= 1; r >>= 1;
		        }
		        return op.apply(sumLeft, sumRight);
		    }

		    public S allProd() {
		        return data[1];
		    }

		    public int maxRight(int l, java.util.function.Predicate<S> f) {
		        inclusiveRangeCheck(l);
		        if (!f.test(E)) {
		            throw new IllegalArgumentException("Identity element must satisfy the condition.");
		        }
		        if (l == MAX) return MAX;
		        l += N;
		        S sum = E;
		        do {
		            l >>= Integer.numberOfTrailingZeros(l);
		            if (!f.test(op.apply(sum, data[l]))) {
		                while (l < N) {
		                    l = l << 1;
		                    if (f.test(op.apply(sum, data[l]))) {
		                        sum = op.apply(sum, data[l]);
		                        l++;
		                    }
		                }
		                return l - N;
		            }
		            sum = op.apply(sum, data[l]);
		            l++;
		        } while ((l & -l) != l);
		        return MAX;
		    }

		    public int minLeft(int r, java.util.function.Predicate<S> f) {
		        inclusiveRangeCheck(r);
		        if (!f.test(E)) {
		            throw new IllegalArgumentException("Identity element must satisfy the condition.");
		        }
		        if (r == 0) return 0;
		        r += N;
		        S sum = E;
		        do {
		            r--;
		            while (r > 1 && (r & 1) == 1) r >>= 1;
		            if (!f.test(op.apply(data[r], sum))) {
		                while (r < N) {
		                    r = r << 1 | 1;
		                    if (f.test(op.apply(data[r], sum))) {
		                        sum = op.apply(data[r], sum);
		                        r--;
		                    }
		                }
		                return r + 1 - N;
		            }
		            sum = op.apply(data[r], sum);
		        } while ((r & -r) != r);
		        return 0;
		    }

		    private void exclusiveRangeCheck(int p) {
		        if (p < 0 || p >= MAX) {
		            throw new IndexOutOfBoundsException(
		                String.format("Index %d out of bounds for the range [%d, %d).", p, 0, MAX)
		            );
		        }
		    }

		    private void inclusiveRangeCheck(int p) {
		        if (p < 0 || p > MAX) {
		            throw new IndexOutOfBoundsException(
		                String.format("Index %d out of bounds for the range [%d, %d].", p, 0, MAX)
		            );
		        }
		    }
		}

	static class InputReader { 
		private InputStream in;
		private byte[] buffer = new byte[1024];
		private int curbuf;
		private int lenbuf;
		public InputReader(InputStream in) {
			this.in = in;
			this.curbuf = this.lenbuf = 0;
		}
		public boolean hasNextByte() {
			if (curbuf >= lenbuf) {
				curbuf = 0;
				try {
					lenbuf = in.read(buffer);
				} catch (IOException e) {
					throw new InputMismatchException();
				}
				if (lenbuf <= 0)
					return false;
			}
			return true;
		}
 
		private int readByte() {
			if (hasNextByte())
				return buffer[curbuf++];
			else
				return -1;
		}
 
		private boolean isSpaceChar(int c) {
			return !(c >= 33 && c <= 126);
		}
 
		private void skip() {
			while (hasNextByte() && isSpaceChar(buffer[curbuf]))
				curbuf++;
		}
 
		public boolean hasNext() {
			skip();
			return hasNextByte();
		}
 
		public String next() {
			if (!hasNext())
				throw new NoSuchElementException();
			StringBuilder sb = new StringBuilder();
			int b = readByte();
			while (!isSpaceChar(b)) {
				sb.appendCodePoint(b);
				b = readByte();
			}
			return sb.toString();
		}
 
		public int nextInt() {
			if (!hasNext())
				throw new NoSuchElementException();
			int c = readByte();
			while (isSpaceChar(c))
				c = readByte();
			boolean minus = false;
			if (c == '-') {
				minus = true;
				c = readByte();
			}
			int res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res = res * 10 + c - '0';
				c = readByte();
			} while (!isSpaceChar(c));
			return (minus) ? -res : res;
		}
 
		public long nextLong() {
			if (!hasNext())
				throw new NoSuchElementException();
			int c = readByte();
			while (isSpaceChar(c))
				c = readByte();
			boolean minus = false;
			if (c == '-') {
				minus = true;
				c = readByte();
			}
			long res = 0;
			do {
				if (c < '0' || c > '9')
					throw new InputMismatchException();
				res = res * 10 + c - '0';
				c = readByte();
			} while (!isSpaceChar(c));
			return (minus) ? -res : res;
		}
 
		public double nextDouble() {
			return Double.parseDouble(next());
		}
 
		public int[] nextIntArray(int n) {
			int[] a = new int[n];
			for (int i = 0; i < n; i++)
				a[i] = nextInt();
			return a;
		}
		public double[] nextDoubleArray(int n) {
			double[] a = new double[n];
			for (int i = 0; i < n; i++)
				a[i] = nextDouble();
			return a;
		}
		public long[] nextLongArray(int n) {
			long[] a = new long[n];
			for (int i = 0; i < n; i++)
				a[i] = nextLong();
			return a;
		}
 
		public char[][] nextCharMap(int n, int m) {
			char[][] map = new char[n][m];
			for (int i = 0; i < n; i++)
				map[i] = next().toCharArray();
			return map;
		}
	}
}
class MinCostFlow {
    private static final class InternalWeightedCapEdge {
        final int to, rev;
        long cap;
        final long cost;
        InternalWeightedCapEdge(int to, int rev, long cap, long cost) { this.to = to; this.rev = rev; this.cap = cap; this.cost = cost; }
    }

    public static final class WeightedCapEdge {
        public final int from, to;
        public final long cap, flow, cost;
        WeightedCapEdge(int from, int to, long cap, long flow, long cost) { this.from = from; this.to = to; this.cap = cap; this.flow = flow; this.cost = cost; }
        @Override
        public boolean equals(Object o) {
            if (o instanceof WeightedCapEdge) {
                WeightedCapEdge e = (WeightedCapEdge) o;
                return from == e.from && to == e.to && cap == e.cap && flow == e.flow && cost == e.cost;
            }
            return false;
        }
    }

    private static final class IntPair {
        final int first, second;
        IntPair(int first, int second) { this.first = first; this.second = second; }
    }

    public static final class FlowAndCost {
        public final long flow, cost;
        FlowAndCost(long flow, long cost) { this.flow = flow; this.cost = cost; }
        @Override
        public boolean equals(Object o) {
            if (o instanceof FlowAndCost) {
                FlowAndCost c = (FlowAndCost) o;
                return flow == c.flow && cost == c.cost;
            }
            return false;
        }
    }

    static final long INF = Long.MAX_VALUE;

    private final int n;
    private final java.util.ArrayList<IntPair> pos;
    private final java.util.ArrayList<InternalWeightedCapEdge>[] g;

    @SuppressWarnings("unchecked")
    public MinCostFlow(int n) {
        this.n = n;
        this.pos = new java.util.ArrayList<>();
        this.g = new java.util.ArrayList[n];
        for (int i = 0; i < n; i++) {
            this.g[i] = new java.util.ArrayList<>();
        }
    }

    public int addEdge(int from, int to, long cap, long cost) {
        rangeCheck(from, 0, n);
        rangeCheck(to, 0, n);
        nonNegativeCheck(cap, "Capacity");
        nonNegativeCheck(cost, "Cost");
        int m = pos.size();
        pos.add(new IntPair(from, g[from].size()));
        int fromId = g[from].size();
        int toId = g[to].size();
        if (from == to) toId++;
        g[from].add(new InternalWeightedCapEdge(to, toId, cap, cost));
        g[to].add(new InternalWeightedCapEdge(from, fromId, 0L, -cost));
        return m;
    }

    private InternalWeightedCapEdge getInternalEdge(int i) {
        return g[pos.get(i).first].get(pos.get(i).second);
    }

    private InternalWeightedCapEdge getInternalEdgeReversed(InternalWeightedCapEdge e) {
        return g[e.to].get(e.rev);
    }
    
    public WeightedCapEdge getEdge(int i) {
        int m = pos.size();
        rangeCheck(i, 0, m);
        InternalWeightedCapEdge e = getInternalEdge(i);
        InternalWeightedCapEdge re = getInternalEdgeReversed(e);
        return new WeightedCapEdge(re.to, e.to, e.cap + re.cap, re.cap, e.cost);
    }

    public WeightedCapEdge[] getEdges() {
        WeightedCapEdge[] res = new WeightedCapEdge[pos.size()];
        java.util.Arrays.setAll(res, this::getEdge);
        return res;
    }

    public FlowAndCost minCostMaxFlow(int s, int t) {
        return minCostFlow(s, t, INF);
    }
    public FlowAndCost minCostFlow(int s, int t, long flowLimit) {
        return minCostSlope(s, t, flowLimit).getLast();
    }
    java.util.LinkedList<FlowAndCost> minCostSlope(int s, int t) {
        return minCostSlope(s, t, INF);
    }

    public java.util.LinkedList<FlowAndCost> minCostSlope(int s, int t, long flowLimit) {
        rangeCheck(s, 0, n);
        rangeCheck(t, 0, n);
        if (s == t) {
            throw new IllegalArgumentException(
                String.format("%d and %d is the same vertex.", s, t)
            );
        }
        long[] dual = new long[n];
        long[] dist = new long[n];
        int[] pv = new int[n];
        int[] pe = new int[n];
        boolean[] vis = new boolean[n];
        long flow = 0;
        long cost = 0, prev_cost = -1;
        java.util.LinkedList<FlowAndCost> result = new java.util.LinkedList<>();
        result.addLast(new FlowAndCost(flow, cost));
        while (flow < flowLimit) {
            if (!dualRef(s, t, dual, dist, pv, pe, vis)) break;
            long c = flowLimit - flow;
            for (int v = t; v != s; v = pv[v]) {
                c = Math.min(c, g[pv[v]].get(pe[v]).cap);
            }
            for (int v = t; v != s; v = pv[v]) {
                InternalWeightedCapEdge e = g[pv[v]].get(pe[v]);
                e.cap -= c;
                g[v].get(e.rev).cap += c;
            }
            long d = -dual[s];
            flow += c;
            cost += c * d;
            if (prev_cost == d) {
                result.removeLast();
            }
            result.addLast(new FlowAndCost(flow, cost));
            prev_cost = cost;
        }
        return result;
    }

    private boolean dualRef(int s, int t, long[] dual, long[] dist, int[] pv, int[] pe, boolean[] vis) {
        java.util.Arrays.fill(dist, INF);
        java.util.Arrays.fill(pv, -1);
        java.util.Arrays.fill(pe, -1);
        java.util.Arrays.fill(vis, false);
        class State implements Comparable<State> {
            final long key;
            final int to;
            State(long key, int to) { this.key = key; this.to = to; }
            public int compareTo(State q) {
                return key > q.key ? 1 : -1;
            }
        };
        java.util.PriorityQueue<State> pq = new java.util.PriorityQueue<>();
        dist[s] = 0;
        pq.add(new State(0L, s));
        while (pq.size() > 0) {
            int v = pq.poll().to;
            if (vis[v]) continue;
            vis[v] = true;
            if (v == t) break;
            for (int i = 0, deg = g[v].size(); i < deg; i++) {
                InternalWeightedCapEdge e = g[v].get(i);
                if (vis[e.to] || e.cap == 0) continue;
                long cost = e.cost - dual[e.to] + dual[v];
                if (dist[e.to] - dist[v] > cost) {
                    dist[e.to] = dist[v] + cost;
                    pv[e.to] = v;
                    pe[e.to] = i;
                    pq.add(new State(dist[e.to], e.to));
                }
            }
        }
        if (!vis[t]) {
            return false;
        }

        for (int v = 0; v < n; v++) {
            if (!vis[v]) continue;
            dual[v] -= dist[t] - dist[v];
        }
        return true;
    }

    private void rangeCheck(int i, int minInlusive, int maxExclusive) {
        if (i < 0 || i >= maxExclusive) {
            throw new IndexOutOfBoundsException(
                String.format("Index %d out of bounds for length %d", i, maxExclusive)
            );
        }
    }

    private void nonNegativeCheck(long cap, java.lang.String attribute) {
        if (cap < 0) {
            throw new IllegalArgumentException(
                String.format("%s %d is negative.", attribute, cap)
            );
        }
    }
}
0