跳到正文

题解

题解:P3992 [BJOI2017] 开车

Shellchen约 4 分钟
原文

这是 2026年10月2日 存档的第 3 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2026年9月20日
收录
2026年9月21日
更新
2026年11月18日
篇幅
约 4 分钟
获赞
18
题目
P3992

版本

  1. v4当前
  2. v3
  3. v2
  4. v1

Computers are fast nowadays, so we can solve this problem in O(nq).\text{Computers are fast nowadays, so we can solve this problem in}\ O(nq)\text{.}

It is important to make sure your program uses SIMD instructions.\text{It is important to make sure your program uses SIMD instructions.}

考虑朴素暴力怎么做。显然是把 a,ba,b 排序后,计算 ∑i=1n∣ai−bi∣\sum_{i=1}^n |a_i-b_i|。

接下来考虑带修的情况。由于单点修,我们不需要每次重新排序,只需要修改后移动即可。

发现移动和求和都可以指令集优化,vector 神力即可。

复杂度 O(nq)O(nq) 带 18\frac18 常数,随便跑。

code
C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
#define ui unsigned int
#define i128 __int128_t
#define u128 __uint128_t
#define i16 short
#define u16 unsigned i16
#define fi first
#define se second
#define pii pair<int,int>
#define lowbit(x) ((x)&(-(x)))
#ifdef int
#define i32 signed
#define u32 unsigned i32
#define inf 1e18
#define popc(x) __builtin_popcountll(x)
#define ctz(x) __builtin_ctzll(x)
#define clz(x) __builtin_clzll(x)
#else
#define ll long long
#define ull unsigned ll
#define inf 1e9
#define infl 1e18
#define popc(x) __builtin_popcount(x)
#define ctz(x) __builtin_ctz(x)
#define clz(x) __builtin_clz(x)
#define popcl(x) __builtin_popcountll(x)
#define ctzl(x) __builtin_ctzll(x)
#define clzl(x) __builtin_clzll(x)
#define pll pair<ll,ll>
#endif
#define double long double
#define sqrt(x) sqrtl(x)
#define cbrt(x) cbrtl(x)
#define pow(x,y) powl(x,y)
#define sin(x) sinl(x)
#define cos(x) cosl(x)
#define tan(x) tanl(x)
#define push emplace
#define pb emplace_back
#define pf emplace_front
#define ppb pop_back
#define ppf pop_front
const int N=1e6+10,mod=1e9+7;
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0),cout.tie(0);
	int n;
	cin>>n;
	vector<int>a(n),b(n),ta(n);
	for(int i=0;i<n;i++) cin>>a[i];
	for(int i=0;i<n;i++) cin>>b[i],ta[i]=a[i];
	sort(a.begin(),a.end());
	sort(b.begin(),b.end());
	int q;
	cin>>q;
	while(q--)
	{
		int i,x;
		cin>>i>>x;
		auto p=lower_bound(a.begin(),a.end(),ta[i]);
		a.erase(p);
		ta[i]=x;
		p=lower_bound(a.begin(),a.end(),ta[i]);
		a.insert(p,x);
		int ans=0;
		for(int i=0;i<n;i++) ans+=abs(a[i]-b[i]);
		cout<<ans<<'\n';
	}
	return 0;
}