zoukankan      html  css  js  c++  java
  • Codeforces 433C. Ryouko's Memory Note (中位数,瞎搞,思维)

    题目链接:

    http://codeforces.com/problemset/problem/433/C

    题意:

    给你一堆数字,允许你修改相同的数字成为别的数字,也可以修改成自己,问你修改后相邻数字的距离的绝对值的和最小是多少。

    思路:

    首先明确一个结论,一个数轴上一些点,要求一个与他们距离之和尽量小的点,那么这个点就是这些点的中位数,即排序后位于中间的数。

    这题的思路是把每一个数的与之相邻的保存下来,为了方便,可以用vector数组。然后为了使得距离之和最短,要取中位数。在一串数字中,距所有数字距离之和最短的就是中位数了,这点应该很好理解。然后把该值修改为该中位数,然后最后找出能使值减少的最大的就是最终要修改的值。

    代码:

    #include<bits/stdc++.h>
    using namespace std;
    typedef long long ll;
    #define MS(a) memset(a,0,sizeof(a))
    #define MP make_pair
    #define PB push_back
    const int INF = 0x3f3f3f3f;
    const ll INFLL = 0x3f3f3f3f3f3f3f3fLL;
    inline ll read(){
        ll x=0,f=1;char ch=getchar();
        while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
        while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
        return x*f;
    }
    //////////////////////////////////////////////////////////////////////////
    const int maxn = 1e5+10;
    
    ll n,m,a[maxn];
    vector<int> g[maxn];
    
    int main(){
        cin >> n >> m;
        ll mi=INF,mx=-1,sum=0;
        for(int i=1; i<=m; i++){
            cin >> a[i];
            mi = min(mi,a[i]); mx = max(mx,a[i]);
            if(i!=1 && a[i]!=a[i-1]) {
                sum += abs(a[i]-a[i-1]);
                g[a[i]].push_back(a[i-1]);
                g[a[i-1]].push_back(a[i]);
            }
        }
        ll ans = sum;
        for(ll i=mi; i<=mx; i++){
            ll tmp = sum;
            int sz = g[i].size();
            if(sz == 0) continue;
            sort(g[i].begin(),g[i].end());
            ll x = g[i][sz/2];
            for(int j=0; j<(int)g[i].size(); j++){
                int t = g[i][j];
                tmp += abs(x-t)-abs(i-t);
            }
            ans = min(ans,tmp);
        }
        cout << ans << endl;
    
    
        return 0;
    }
  • 相关阅读:
    Understanding about Baire Category Theorem
    Isometric embedding of metric space
    Convergence theorems for measurable functions
    Mindmap for "Principles of boundary element methods"
    Various formulations of Maxwell equations
    Existence and uniqueness theorems for variational problems
    Kernels and image sets for an operator and its dual
    [loj6498]农民
    [luogu3781]切树游戏
    [atAGC051B]Three Coins
  • 原文地址:https://www.cnblogs.com/yxg123123/p/7236966.html
Copyright © 2011-2022 走看看