列表

详情


NC50544. 打印文章

描述

给出N个单词,每个单词有个非负权值C_i,现要将它们分成连续的若干段,每段的代价为此段单词的权值和的平方,还要加一个常数M,即。现在想求出一种最优方案,使得总费用之和最小。

输入描述

包含多组测试数据,对于每组测试数据:
第一行包含两个整数N和M。
第二行为N个整数。

输出描述

输出仅一个整数,表示最小的价值。

示例1

输入:

5 5
5 9 5 7 5

输出:

230

原站题解

上次编辑到这里,代码来自缓存 点击恢复默认模板

Java(javac 1.8) 解法, 执行用时: 610ms, 内存消耗: 51676K, 提交时间: 2021-03-06 10:22:44

import java.io.*;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.LockSupport;

public class Main {

    static class Task {

        public static String roundS(double result, int scale) {
            String fmt = String.format("%%.%df", scale);
            return String.format(fmt, result);
            //        DecimalFormat df = new DecimalFormat("0.000000");
            //        double result = Double.parseDouble(df.format(result));
        }

        int rt(int x) {
            if (x != fa[x]) {
                int to = rt(fa[x]);
                //     dp[x] ^= dp[fa[x]];
                fa[x] = to;
                return to;
            }

            return x;
        }

        void combine(int x, int y, int val) {
            int rt1 = rt(x);
            int rt2 = rt(y);

            if (rt1 == rt2)
                return;

            fa[rt1] = rt2;
            //    dp[rt1] = dp[x] ^ dp[y] ^ val;
            g--;

        }


        int fa[];
        int g;


        static int MAXN = 10000;
        static Random rd = new Random(348957438574659L);

        static int[] ch[], val, size, rnd, cnt;
        static int len = 0, rt = 0;

        // return new node, the node below s
        static int rotate(int s, int d) {
            // child
            int x = ch[s][d ^ 1];
            // give me grandson
            ch[s][d ^ 1] = ch[x][d];
            // child become father
            ch[x][d] = s;
            // update size, update new son first
            update(s);
            update(x);
            return x;
        }

        static void update(int s) {
            size[s] = size[ch[s][0]] + size[ch[s][1]] + cnt[s];
        }

        // 0 for left, 1 for right
        static int cmp(int x, int num) {
            if (val[x] == num)
                return -1;

            return num < val[x] ? 0 : 1;
        }

        static int insert(int s, int num) {
            if (s == 0) {
                s = ++len;
                val[s] = num;
                size[s] = 1;
                rnd[s] = rd.nextInt();
                cnt[s] = 1;
            } else {
                int d = cmp(s, num);

                if (d != -1) {
                    ch[s][d] = insert(ch[s][d], num);

                    // father's random should be greater
                    if (rnd[s] < rnd[ch[s][d]]) {
                        s = rotate(s, d ^ 1);
                    } else {
                        update(s);
                    }
                } else {
                    ++cnt[s];
                    ++size[s];
                }
            }

            return s;
        }

        static int del(int s, int num) {
            int d = cmp(s, num);

            if (d != -1) {
                ch[s][d] = del(ch[s][d], num);
                update(s);
            } else if (ch[s][0] * ch[s][1] == 0) {
                if (--cnt[s] == 0) {
                    s = ch[s][0] + ch[s][1];
                }
            } else {
                int k = rnd[ch[s][0]] < rnd[ch[s][1]] ? 0 : 1;
                // k points to smaller random value,then bigger one up
                s = rotate(s, k);
                // now the node with value num become the child
                ch[s][k] = del(ch[s][k], num);
                update(s);
            }

            return s;
        }

        static int getKth(int s, int k) {
            int lz = size[ch[s][0]];

            if (k >= lz + 1 && k <= lz + cnt[s]) {
                return val[s];
            } else if (k <= lz) {
                return getKth(ch[s][0], k);
            } else {
                return getKth(ch[s][1], k - lz - cnt[s]);
            }
        }

        static int getRank(int s, int value) {
            if (s == 0)
                return 1;

            if (value == val[s])
                return size[ch[s][0]] + 1;

            if (value < val[s])
                return getRank(ch[s][0], value);

            return getRank(ch[s][1], value) + size[ch[s][0]] + cnt[s];
        }


        static int getPre(int data) {
            int ans = -1;
            int p = rt;

            while (p > 0) {
                if (data > val[p]) {
                    if (ans == -1 || val[p] > val[ans])
                        ans = p;

                    p = ch[p][1];
                } else
                    p = ch[p][0];
            }

            return ans != -1 ? val[ans] : (-2147483647);
        }

        static int getNext(int data) {
            int ans = -1;
            int p = rt;

            while (p > 0) {
                if (data < val[p]) {
                    if (ans == -1 || val[p] < val[ans])
                        ans = p;

                    p = ch[p][0];
                } else
                    p = ch[p][1];
            }

            return ans != -1 ? val[ans] : 2147483647;
        }


        static boolean find(int s, int num) {
            while (s != 0) {
                int d = cmp(s, num);

                if (d == -1)
                    return true;
                else
                    s = ch[s][d];
            }

            return false;
        }
        static int ans = -10000000;
        static boolean findX(int s, int num) {
            while (s != 0) {
                if (val[s] <= num) {
                    ans = num;
                }

                int d = cmp(s, num);

                if (d == -1)
                    return true;
                else {
                    s = ch[s][d];
                }
            }

            return false;
        }

        long gcd(long a, long b) {
            if (b == 0)
                return a;

            return gcd(b, a % b);
        }


        void linear_sort(int arr[]) {
            int d =  65536;
            ArrayDeque bucket[] = new ArrayDeque[d];

            for (int j = 0; j < d; ++j) {
                bucket[j] = new ArrayDeque();
            }

            for (int u : arr) {
                bucket[u % d].offer(u);
            }

            int pos = 0;

            for (int j = 0; j < d; ++j) {
                while (bucket[j].size() > 0) {
                    arr[pos++] = (int)bucket[j].pollFirst();
                }
            }

            for (int u : arr) {
                bucket[u / d].offer(u);
            }

            pos = 0;

            for (int j = 0; j < d; ++j) {
                while (bucket[j].size() > 0) {
                    arr[pos++] = (int)bucket[j].pollFirst();
                }
            }
        }

        int cur  = 0;
        int h[];
        int to[];
        int ne[];
        void add(int u, int v) {
            to[cur] = v;
            ne[cur] = h[u];
            h[u] = cur++;
        }


        public boolean dfs(String cur, HashMap<String, Integer> vis, Map<String, List<String>> list, int cl) {

            vis.put(cur, cl);

            for (String hp : list.get(cur)) {
                if (vis.containsKey(hp)) {
                    if (vis.get(hp) == cl) {
                        return false;
                    }

                } else {
                    if (!dfs(hp, vis, list, 1 - cl)) {
                        return false;
                    }
                }
            }

            return true;

        }


        public class MultiSet {

            TreeMap<Integer, Integer> map;
            int ct = 0;
            MultiSet() {
                map = new TreeMap<>();
            }

            public void remove(int key) {
                if (map.containsKey(key)) {
                    int times = map.get(key);

                    if (times == 1) {
                        map.remove(key);
                    } else {
                        map.put(key, times - 1);
                    }

                    ct--;
                }
            }

            public void add(int key) {
                map.put(key, map.getOrDefault(key, 0) + 1);
                ct++;
            }

            public int last() {
                return map.lastKey();
            }

            public int first() {
                return map.firstKey();
            }

            public int size() {
                return ct;
            }

        }




        int color[], dfn[], low[], stack[];
        int sccno[];

        boolean iscut[];
        int time = 0, top = 0;
        int scc_cnt;
        int  dcc_cnt;
        List<Integer> dcc[];
        int root = 0;
        //  无向图的强连通分量
        void tarjanNonDirect(int u) {
            low[u] = dfn[u] = ++time;
            stack[top++] = u;
            int child = 0;

            for (int i = h[u]; i != -1; i = ne[i]) {
                int v = to[i];

                if (dfn[v] == 0) {
                    tarjanNonDirect(v);
                    low[u] = Math.min(low[u], low[v]);

                    if (low[v] >= dfn[u]) {
                        if (u != root || ++child > 1) { // 不是root,直接记为cut,是root,判断是否有两个儿子
                            iscut[u] = true;
                        }

                        ++dcc_cnt;
                        // 一个割点可能会被多个点双共享
                        int z = -1;

                        do {
                            z = stack[--top];
                            //dcc[dcc_cnt].add(z);
                        } while (z != v);

                        //dcc[dcc_cnt].add(u);
                    }
                } else {
                    low[u] = Math.min(low[u], dfn[v]);
                    // 没有特判是否直接指向父亲
                    // 回边,使用dfn【v】更新low【u】,因为可能是指向父亲,而父亲的low可能比较小
                }
            }
        }

        long dp11[][];
        public long s(int l, int r, int a[]) {
            if (l > r)
                return 0;

            if (dp11[l][r] != 0) {
                return dp11[l][r];
            }

            if (l == r) {
                return dp11[l][r] = a[l];
            }

            return dp11[l][r] = Math.max((long)a[l] - s(l + 1, r, a), (long)a[r] - s(l, r - 1, a));
        }


        int dp[][];
        public void solve(int testNumber, InputReader in, PrintWriter out) {
int fk = 1;int n;long s;

            int q[] = new int[500010];

        while(true) {
            try {
                n = in.nextInt();
                s = in.nextLong();
            }catch (Exception e){
                break;
            }
            long c[] = new long[n + 1];

            for (int i = 1; i <= n; ++i) {

                c[i] = in.nextLong();

                c[i] = c[i] + c[i - 1];
            }

            long dp[] = new long[n + 1];



            int st = 0;
            int e = 0;
            q[e++] = 0;

            for (int i = 1; i <= n; ++i) {

                // dp[i] = t[i]*(c[i] - c[0]) + s * (c[n-1] -c[0]);
//                for(int j=0;j<i;++j){
//                    dp[i] = Math.min(dp[i] , dp[j] + c[i]2 + c[j]2 - 2c[i]*c[j] + s))

 //                      dp[j] + c[j]2 = dp[i] -c[i]2 + 2*c[i] * c[j] -s;
//                    dp[i] = Math.min(dp[i] , dp[j] + (c[i]-c[j])*(t[i]) + s *(c[n-1] - c[j]));
//
//                }

//                dp[i] = dp[q[st]] + (c[i] - c[q[st]] + s);
//
//                while(st<e && dp[q[e-1]] -  c[q[e-1]] >= dp[i]  - c[i]) e--;
//
//                q[e++] = i;


//                while (st + 1 < e && (dp[q[st + 1]] + c[q[st+1]]*c[q[st+1]] - dp[q[st]] - c[q[st]]*c[q[st]]) <= (c[q[st + 1]] - c[q[st]]) * (2*c[i])) st++;


                int lo = 0;
                int hi =  e-1;
                while(lo<hi){
                    int mi = (lo+hi)>>1;
                    if(dp[q[mi+1]] + c[q[mi+1]]*c[q[mi+1]] - (dp[q[mi]] + c[q[mi]]*c[q[mi]]) <= 2*c[i]*(c[q[mi+1]]-c[q[mi]])){
                        lo = mi+1;
                    }else{
                        hi = mi;
                    }
                }

                dp[i] = dp[q[lo]] + c[i]*c[i] + c[q[lo]]*c[q[lo]] - 2*c[i]*c[q[lo]] + s;

                while (st + 1 < e && (c[i] - c[q[e - 1]]) * (dp[q[e - 1]]  + c[q[e-1]]*c[q[e-1]] - dp[q[e - 2]] - c[q[e-2]]*c[q[e-2]]) - (dp[i] + c[i]*c[i] - dp[q[e - 1]] -  c[q[e-1]]*c[q[e-1]]) * (c[q[e - 1]] - c[q[e - 2]]) >= 0)
                    e--;

                q[e++] = i;


            }
            out.println(dp[n]);

        }


        }


        static long mul(long a, long b, long p) {
            long res = 0, base = a;

            while (b > 0) {
                if ((b & 1L) > 0)
                    res = (res + base) % p;

                base = (base + base) % p;
                b >>= 1;
            }

            return res;
        }

        static long mod_pow(long k, long n, long p) {
            long res = 1L;
            long temp = k % p;

            while (n != 0L) {
                if ((n & 1L) == 1L) {
                    res = mul(res, temp, p);
                }

                temp = mul(temp, temp, p);
                n = n >> 1L;
            }

            return res % p;
        }


        public static double roundD(double result, int scale) {
            BigDecimal bg = new BigDecimal(result).setScale(scale, RoundingMode.UP);
            return bg.doubleValue();
        }



    }
    private static void solve() {
        InputStream inputStream = System.in;
//                InputStream inputStream  = null;
//                try {
//                    inputStream = new FileInputStream(new File("D:\\chrome_download\\exp.out"));
//                } catch (FileNotFoundException e) {
//                    e.printStackTrace();
//                }
        OutputStream outputStream = System.out;
//                OutputStream outputStream = null;
//                File f = new File("D:\\chrome_download\\");
//                try {
//                    f.createNewFile();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                try {
//                    outputStream = new FileOutputStream(f);
//                } catch (FileNotFoundException e) {
//                    e.printStackTrace();
//                }
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        Task task = new Task();
        task.solve(1, in, out);
        out.close();
    }
    public static void main(String[] args) {
        new Thread(null, () -> solve(), "1", (1 << 30)).start();
        // solve();
    }
    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;
        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }
        public String nextLine() {
            String line = null;

            try {
                line = reader.readLine();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            return line;
        }
        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            return tokenizer.nextToken();
        }
        public int nextInt() {
            return Integer.parseInt(next());
        }
        public char nextChar() {
            return next().charAt(0);
        }
        public int[] nextArray(int n) {
            int res[] = new int[n];

            for (int i = 0; i < n; ++i) {
                res[i] = nextInt();
            }

            return res;
        }
        public long nextLong() {
            return Long.parseLong(next());
        }
        public double nextDouble() {
            return Double.parseDouble(next());
        }
    }
}

C++(clang++ 11.0.1) 解法, 执行用时: 152ms, 内存消耗: 10096K, 提交时间: 2023-07-20 11:41:02

#include<bits/stdc++.h>
#define maxn 500003
using namespace std;
typedef long long ll;
int q[maxn];
ll sum[maxn],dp[maxn];
int getX(const int &i,const int &j){
	return sum[j] - sum[i];
}
ll getY(const int &i,const int &j){
	return dp[j] + sum[j] * sum[j] - dp[i] - sum[i] * sum[i];
}
int main(){
	int n,m,head,tail,i;
	while (cin>>n>>m){
		for (i = 1;i <= n;i++){
			cin>>sum[i];
			sum[i] += sum[i - 1];
		}
		head = tail = 0;
		for (i = 1;i <= n;i++){
			while (head < tail && getY(q[head],q[head+1]) <=
								  (getX(q[head],q[head+1])*sum[i]<<1))
				head++;
			dp[i]=dp[q[head]]+(sum[i]-sum[q[head]])*(sum[i]-sum[q[head]])+m;
			while (head < tail && getX(q[tail],i)*getY(q[tail-1],q[tail]) >=
								  getX(q[tail-1],q[tail])*getY(q[tail],i))
				tail--;
			q[++tail] = i;
		}
		cout<<dp[n]<<endl;
	}
	return 0;
}

上一题