AcWing 1987.粉刷栅栏(离散化,差分)

题目链接

https://www.acwing.com/problem/content/1989/

思路

差分,但是数据范围很大,需要开map进行处理。

AC代码

#include <iostream>
#include <algorithm>
#include <cstring>
#include <map>
using namespace std;
int n;
map<int, int>b;
int main(int argc, char* argv[])
{
	cin >> n;
	int x = 0;//记录当前位置
	while (n--)
	{
		int t;
		char s;
		cin >> t >> s;
		if(s=='R')
		{
			b[x]++;
			b[x + t]--;
			x += t;
		}
		else
		{
			b[x - t]++;
			b[x]--;
			x -= t;
		}
	}
	int res = 0;
	int sum = 0;
	int last;
	for(auto& [i,j]: b)
	{
		if (sum >= 2)//被粉刷的总数大于等于2层
			res += i - last;//答案加上现在这一层减上一层的数量
		sum += j;//加上被标记的这一结点的数量
		last = i;//记录遍历过的这个结点
	}
	cout << res;
}

心得

不太懂离散化是啥诶。。

posted @ 2022-01-26 11:41  张牧歌  阅读(35)  评论(1编辑  收藏  举报