zoukankan      html  css  js  c++  java
  • 16.1113 模拟考试T1

    笔记
    【问题描述】
    给定一个长度为m的序列a,下标编号为1~m。序列的每个元素都是1~N的
    整数。定义序列的代价为累加(1->m-1 abs(ai+1-ai))
    你现在可以选择两个数x和y,并将序列?中所有的x改成y。x可以与y相等。
    请求出序列最小可能的代价。
    【输入格式】
    输入第一行包含两个整数n和m。第二行包含n个空格分隔的整数,代表序
    列a。
    【输出格式】
    输出一行,包含一个整数,代表序列最小的代价。
    【样例输入 1】
    4 6
    1 2 3 4 3 2
    【样例输出 1】
    3
    【样例输入 2】
    10 5
    9 4 3 8 8
    【样例输出 1】
    6
    【样例解释】
    样例 1 中,最优策略为将 4 改成 3。样例 2 中,最优策略为将 9 改成 4。
    【数据规模和约定】
    对于30%的数据,n,m<=100
    对于60%的数据,n,m ≤ 2000。
    对于100%的数据,1 ≤ n,m ≤ 100,000。

     1 #include <cstdio>
     2 #include <iostream>
     3 #include <algorithm>
     4 #include <ios>
     5 #include <vector>
     6 using namespace std;
     7 typedef long long ll;
     8 const int N = (int)1e5;
     9 int n, m, a[N+1];
    10 vector<int> b[N+1];
    11 int main(int argc, char *argv[]) {
    12     freopen("note.in", "r", stdin);
    13     freopen("note.out", "w", stdout);
    14 
    15     ios :: sync_with_stdio(false);
    16     cin>>n>>m;
    17     for (int i=1;i<=m;++i) cin>>a[i];
    18     for (int i=1;i<=m;++i) {
    19         if (i>1&&a[i-1]!=a[i]) b[a[i-1]].push_back(a[i]);
    20         if (i<m&&a[i+1]!=a[i]) b[a[i+1]].push_back(a[i]);
    21     }
    22 
    23     ll ans=0LL,sum=0LL;
    24     for (int i=1;i<=n;++i){
    25         if (!b[i].size()) continue;
    26         sort(b[i].begin(),b[i].end());
    27         int y=b[i][b[i].size()>>1];
    28         ll before=0LL,after=0LL;
    29         for (int j=0;j<b[i].size();++j) {
    30             before+=abs(i-b[i][j]);
    31             after+=abs(y-b[i][j]);
    32         }
    33         ans=max(ans,before-after),sum+=before;
    34     }
    35     cout<<sum/2-ans<<endl;
    36     fclose(stdin);
    37     fclose(stdout);
    38     return 0;
    39 }

     思路:动态数组记录下与每个数字相邻的所有数字,若是要修改这这个数字的话,肯定是从与它相邻的数字中间取中位数(先sort)这样对于答案的贡献肯定最小,before记录改之前的值,sum记录所有改之前的值,sum/2是因为相邻的两个数字肯定是互相相邻的,即每一个数字都被计算了两遍,ans记录对答案贡献较大的修改值,即遍历一遍检查修改1-N中的哪个数字,可以使答案更优,before-after为将i修改为

    int y=b[i][b[i].size()>>1]前后差值,即修改i对答案的优化程度

     数据:见网盘我叫雷锋~  提取密码:gmcf

  • 相关阅读:
    static_cast与dynamic_cast的联系与区别
    ActiveX控件实现
    Foundation: Rapid Prototyping and Building Framework from ZURB
    Python datetime / time conversions « SaltyCrane Blog
    Extending Django’s database API to include fulltext search
    解决linux下/etc/rc.local开机器不执行的原因。
    巧用 /etc/rc.local,开机时完成一些自动任务 GNU/Linux,Windows的終結者 KM大宝 和讯博客
    Kill process by name in python Stack Overflow
    Linux iostat监测IO状态
    An Introduction to Python: File I/O
  • 原文地址:https://www.cnblogs.com/suishiguang/p/6058879.html
Copyright © 2011-2022 走看看