Week5 B - TT's Magic Cat

问题描述:

Thanks to everyone’s help last week, TT finally got a cute cat. But what TT didn’t expect is that this is a magic cat.
One day, the magic cat decided to investigate TT’s ability by giving a problem to him. That is select n cities from the world map, and a[i] represents the asset value owned by the i-th city.
Then the magic cat will perform several operations. Each turn is to choose the city in the interval [l,r] and increase their asset value by c. And finally, it is required to give the asset value of each city after q operations.
Could you help TT find the answer?

解题思路:

每次操作给出一个区间,对该索引区间内的数组元素同时加减一个值,利用差分数组:
• B[1] = A[1]
• B[i] = A[i] - A[i-1]
可以对该操作进行简化,
• A[L]~A[R] 均加上 c
• 等价于 B[L] += c, B[R+1] -= c
这样就大大降低了复杂度,最后再将利用数组B得到数组A即可。

Input:
The first line contains two integers n,q(1≤n,q≤2⋅105) — the number of cities and operations. The second line contains elements of the sequence a: integer numbers a1,a2,...,an (−106≤ai≤106). Then q lines follow, each line represents an operation. The i-th line contains three integers l,r and c (1≤l≤r≤n,−105≤c≤105) for the i-th operation.

Output:
- Print n integers a1,a2,…,an one per line,
and ai should be equal to the final asset value of the i-th city.

输入示例1:
4 2
-3 6 8 4
4 4 -2
3 3 1

输出示例1:
-3 6 9 2

输入示例2:
2 1
5 -2
1 2 4

输出示例2:
9 2

实验代码:

#include<iostream>
using namespace std;
long long int a[200100];		//原数组 
long long int b[200100];		//差分数组 
int n,q;
void cat()
{
	b[1]=a[1];
	for(int i=2;i<=n;i++)
	{
		b[i]=a[i]-a[i-1];
	}		//差分数组 
	int l,r,c;
	for(int i=0;i<q;i++)
	{
		cin>>l>>r>>c;
		b[l]+=c;
		b[r+1]-=c;
	}
	a[1]=b[1];
	for(int i=2;i<=n;i++)
		a[i]=a[i-1]+b[i];
	for(int i=1;i<=n;i++)
		cout<<a[i]<<" ";
	cout<<endl; 
}
int main(void)
{
	cin>>n>>q;
	for(int i=1;i<=n;i++)		//从1开始 
		cin>>a[i];
	cat(); 
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值