跳到正文

个人记录

SET做法优化版

wanqitzh约 3 分钟
原文
文章信息与版本

文章信息

发布
2021年7月21日
收录
2025年12月12日
更新
2026年11月17日
篇幅
约 3 分钟
获赞
3

版本

  1. v1当前

处理第i天时候,保证前面i-1天的营业额有序,然后查找第i天在其中的位置,跟前后两个差值绝对值中较小的就是当天的波动值了。

代码
需要保证有序,且有频繁的查找,插入操作。这题用STL的set就非常效率且方便

都在代码注释里了

C++
#include<iostream>
#include<set>
#include<cmath>
#include<cstdio>
using namespace std;

int fread()
{
	char ch;
	int x=0, flag = 1;//flag是正负数标记 
	ch= getchar();//读取一个字符,注意空格、换行符也算字符 
	while(ch<'0' || ch>'9')//负号保留,去除数字前的其他无用字符
	{
		if(ch == '-')flag = -1;
		ch = getchar();
	}
	
	while(ch>='0' && ch<='9')//按字符读取数字 
	{
		x= x*10+(ch-'0');//与字符‘0’相减得到对应数字 
		ch = getchar(); 
	}
	return x*flag;//记得跟正负号标记相乘 
}

set<int> a;
long long sum = 0;
int main()
{

	int n;
	n=fread();
	for(int i =1;i<=n;i++)
	{
		int temp;
		temp = fread();
		if(a.empty())//第一天的数据直接放入set 
		{
			sum+=temp;
			a.insert(temp);
			continue;
		}
		set<int>::iterator it = a.lower_bound(temp);//找第一个大于等于temp的数的迭代器位置 
		if(it != a.end())// 找到了 
		{
			if(temp==*it)//跟找到的数相等,波动值为0,无需插入 
			{
				continue;
			}			
			if(it == a.begin())//找到在开始a.begin() 
			{
				sum+=abs(temp-*it);
				a.insert(it,temp);//用it的值插入,避免重新查找位置 
			}
			else
			{	//找到在中间 
				int a1 = abs(temp - *it);
				int a2 = abs(temp - *(--it));
				sum+=min(a1,a2);
				a.insert(++it,temp);
			}
		}
		else//找到在末尾 a.end() 
		{
			sum+=abs(temp - *(--it));
			a.insert(++it,temp);
		}
	}
	cout<<sum;

	return 0;
}