当前位置:网站首页>C. Helping the Nature(cf)差分
C. Helping the Nature(cf)差分
2022-06-21 17:55:00 【璇玑你没有心】
题目大意:给你一个数组a,其中每个数的范围是−1e9≤ai≤1e9,每一次操作可以在以下操作中选择:
1)把a1 ... ai所有数减一
2) 把ai ... an所有数减一
3)把a1...an整个数组中所有数加一
问你最少操作次数使得整个数组中每个元素都为0?
思路:
一段进行减操作/加操作 ----> 差分
所以由a[i]得b[i]数组(每两个相邻的元素之间的差值),因为所有数最后都要变成0,所以b[]数组也应该全为0,所以可以用1或2操作,从后往前把b[]全变为0,每次变完,b[i]之后的b[j]都为0了,也就是数组a[]后面都会变成一样的了;注意如果b[i]此时>=0,那么就是将后面部分减1,所以不用管;但是如果b[i]<0,就是把从a[1]到a[i]全部减1,所以a[1]会变,这里要改变a[1]。最后把b[n]到b[2]变完了,再看a[1]与0的差别,可以分别用2和3操作把整个数组全加或全减变为0!
AC代码:
#include<bits/stdc++.h>
#define INF 0x3f3f3f3f
#define ll long long
#define PII pair<int,int>
#define rep(i, n) for (int i = 1; i <= (n); ++i)
#define rrep(i, n) for(int i = n; i >= 1; ++i)
using namespace std;
const double pi = acos(-1.0);
const int N = 2e5 + 10;
ll a[N], b[N];
int main()
{
int t, n;
cin >> t;
while(t--)
{
cin >> n;
ll res = 0;
rep(i, n) cin >> a[i], b[i] = a[i] - a[i - 1];
for(int i = n; i > 1; i--)
{
if(b[i] >= 0) res += b[i];
else res -= b[i], b[1] += b[i];
}
res += abs(b[1]);
cout << res << endl;
}
return 0;
}
边栏推荐
- Nepal graph has settled in Alibaba cloud computing nest to help enterprises build a super large-scale map database on the cloud
- JDBC基础知识
- Must the database primary key be self incremented? What scenarios do not suggest self augmentation?
- Delete the specified screen
- Second cloud's original fully compatible solution for Xinchuang is upgraded to help accelerate the implementation of Xinchuang industry
- 插入类排序法
- Selection skills of national production reinforced Ethernet switch
- homeassistant addons
- 【面试高频题】难度 1/5,热门枚举类模拟题
- 基于ASP.NET开发的企信通源码 短信管理平台源码
猜你喜欢
Must the database primary key be self incremented? What scenarios do not suggest self augmentation?

The main data products of China's two Fengyun meteorological "new stars" will be open and shared with global users

牛客网:归并两个有序的数组

Canvas dynamic background text luminous JS effect

11 Beautiful Soup 解析庫的簡介及安裝

Ant group's self-developed tee technology has passed the national financial technology product certification, and 47 tests have met the requirements

vivo 容器集群监控系统架构与实践

力扣今日题1108. IP 地址无效化

蚂蚁集团自研TEE技术通过国家级金融科技产品认证 47项检测均达要求

数据库主键一定要自增吗?有哪些场景不建议自增?
随机推荐
Summary of the 13th week
JSP Basics
Excel文件加密的两种方式
WMS仓库仓储管理系统源码
【区间和专题の前缀和】前缀和 + 哈希表 运用题
昇腾科研创新使能计划赋能开发者&nbsp; 华为计算提供三大维度支持
Fpga/cpld final examination paper for the first semester of Nanjing University of information technology 2020-2021
[Shangshui Shuo series] day one
從“村辦企業”到“百億集團”,紅星實業何以完成“蝶變”?
How to apply for SSL certificate using IP
2022 China eye Expo, Shandong Youth eye health exhibition, vision correction and rehabilitation Exhibition
50位中国女性科学家入选2022福布斯
品牌、产品和服务齐发力,东风日产接下来有什么新动作?
【一起上水硕系列】Day One
华为鸿蒙认证测试题,你能答对几道?
Threejs aircraft Earth 3D scene animation
Use the uniapp framework to build the zheliban micro application (single sign on, embedded point, aging adaptation, RPC gateway)
yolov5训练自己的数据集报错记录
蚂蚁集团自研TEE技术通过国家级金融科技产品认证 47项检测均达要求
技术分享 | MySQL:caching_sha2_password 快速问答