zoukankan      html  css  js  c++  java
  • 《算法竞赛进阶指南》0x03差分

    题目链接:https://www.acwing.com/problem/content/102/

    给定一个序列,只能对一个区间加一或者减一,问至少需要多少步使得所有数都变成一致的?有多少种一致序列?

    利用差分,对一个区间进行加一或者减一的话,一定是一个差分+1加上另一个差分-1。

    代码如下:

    #include<bits/stdc++.h>
    using namespace std;
    typedef unsigned int ui;
    typedef long long ll;
    typedef unsigned long long ull;
    #define pf printf
    #define mem(a,b) memset(a,b,sizeof(a))
    #define prime1 1e9+7
    #define prime2 1e9+9
    #define pi 3.14159265
    #define lson l,mid,rt<<1
    #define rson mid+1,r,rt<<1|1
    #define scand(x) scanf("%llf",&x) 
    #define f(i,a,b) for(int i=a;i<=b;i++)
    #define scan(a) scanf("%d",&a)
    #define mp(a,b) make_pair((a),(b))
    #define P pair<int,int>
    #define dbg(args) cout<<#args<<":"<<args<<endl;
    #define inf 0x7ffffff
    inline int read(){
        int ans=0,w=1;
        char ch=getchar();
        while(!isdigit(ch)){if(ch=='-')w=-1;ch=getchar();}
        while(isdigit(ch))ans=(ans<<3)+(ans<<1)+ch-'0',ch=getchar();
        return ans*w;
    }
    int n,m,t;
    const int maxn=1e5+10;
    const ll mod=10000;
    ll a[maxn],d[maxn];
    int main()
    {
    //    freopen("input.txt","r",stdin);
    //    freopen("output.txt","w",stdout);
        n=read();
        f(i,1,n)scanf("%lld",&a[i]);
        d[1]=a[1];
        f(i,2,n)d[i]=a[i]-a[i-1];
        ll p=0,q=0;
        f(i,2,n)
        {
            if(d[i]>0)p+=d[i];
            if(d[i]<0)q-=d[i];
        }//min(p,q)+abs(p,q)=max(p,q) 
        cout<<max(p,q)<<"
    "<<abs(p-q)+1;
    }
  • 相关阅读:
    Python将字符串转换成字典
    MySQL索引、视图
    MySQL高级查询
    MySQL函数应用
    MySQL约束
    MySQL基础查询
    MySQL数据库基本语法
    MySQL数据库存储引擎
    MySQL数据库简介与命令行操作
    MySQL 安装和配置环境变量
  • 原文地址:https://www.cnblogs.com/randy-lo/p/13125114.html
Copyright © 2011-2022 走看看