跳到正文

个人记录

7.11总结

原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月26日
篇幅
约 3 分钟

版本

  1. v1当前

P12725 [KOI 2021 Round 2] 累计距离

本体是要推式子

关键公式为:q*(a[1]+a[2]+…+a[s-1])-(a[1]*x[1]+a[2]*x[2]+…+a[s-1]*x[s-1])+(a[s]*x[s]+a[s+1]*x[s+1]+…+a[n]*x[n])-q *(a[s+1]+a[s+2]+…+a[n]);

而很容易就能发现本体可用前缀和

code

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,T,lc,sum,qzh[200010],qzh2[200010],cc[200010];
struct ll
{
	int x,y;
}a[200010];
bool cmp(ll aa,ll bb)
{
	return aa.y<bb.y;//为了后面二分,这里要排序
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	cin>>n>>T;
	for(int i=1;i<=n;i++)
	{
		cin>>a[i].x>>a[i].y;
	}
	sort(a+1,a+n+1,cmp);
    for(int i=1;i<=n;i++)
    {
    	cc[i]=a[i].y;//lower_bound无法处理结构体,所以提前存储在一个数组里
        qzh[i]=qzh[i-1]+a[i].x*a[i].y;//两种前缀和分开装
        qzh2[i]=qzh2[i-1]+a[i].x;
    }
	while(T--)
	{
		cin>>lc;
		int r=lower_bound(cc+1,cc+n+1,lc)-cc;//二分查找位置
		int q=(lc*qzh2[r-1]-qzh[r-1]),h=((qzh[n]-qzh[r-1])-lc*(qzh2[n]-qzh2[r-1]));//套公式
		cout<<q+h<<"\n";//输出
	}
	return 0;
}

T630306 环数

这道题也是前缀和,不过要特判i+m-1>n的情况。

code

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int T,n,m,a[10010],qzh[10010],maxx,maxi,sum;
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0);cout.tie(0);
	cin>>T;
	while(T--)
	{
		cin>>n>>m;
		for(int i=1;i<=n;i++)
		{
			cin>>a[i];
			qzh[i]=qzh[i-1]+a[i];//先算出前缀和
		}
		maxi=0;
		maxx=LLONG_MIN;
		for(int i=1;i<=n;i++)
		{
			if(i+m-1>n)如果超界了
			{
				sum=qzh[n]-qzh[i-1]+qzh[(i+m-1)%n];//加上从i~n的和,以及剩下的数之和。
			}
			else
			{
				sum=qzh[i+m-1]-qzh[i-1];//如果没超界直接调用前缀和数组
			}
			if(sum>maxx)//如果成为了当前的最大值
			{
				maxi=i;
				maxx=sum;
			}
		}
		cout<<maxx<<" "<<maxi<<"\n";//输出
	}
	return 0;
}
原文