2019年icpc上海网络赛 B Light bulbs (分块、差分)
2024-10-08 17:37:36
https://nanti.jisuanke.com/t/41399
题目大意:
有n个灯,m次操作,每次修改[l,r]内的灯,(off - on ,on - off),问最后有几盏灯亮着.
换种说法:n个点m个区间,每次区间内的数+1,最后n个点中计数为奇数的点的个数就是答案。
刚开始没注意,直接用线段树写,超内存了。。。。
这题因为外层有个T,并且n太大,还要卡内存,太过分了。
卡数据卡内存,每组样例一重循环都会超时。所以可以分块和对m处理来做。
对m处理的话,仔细想一想,只有区间次数被操作奇数次的话,这个区间操作才有效,所以我们只要把左右端点从小到大排序然后区间求和就行了。
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <math.h>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <math.h>
const int INF=0x3f3f3f3f;
typedef long long LL;
const int mod=1e9+;
const int maxn=1e7+;
using namespace std;
int a[]; int main()
{
int T;
scanf("%d",&T);
for(int k=;k<=T;k++)
{
int n,m;
int l,r;
scanf("%d %d",&n,&m);
for(int i=;i<*m;i++)
{
scanf("%d %d",&l,&r);
a[i++]=l;
a[i]=++r;
}
m*=;
int ans=;
sort(a,a+m);
// for(int i=0;i<m;i++)
// {
// printf("%d ",a[i]);
// }
for(int i=;i<m;i+=)
{
ans+=a[i]-a[i-];
}
printf("Case #%d: %d\n",k,ans);
}
return ;
}
对m下手,注意到:
把每一个端点存起来之后(并且排序),毎两个点之间的区间的 亮与否至于左边有关,不包括右边.
所以利用差分的思想,修改 L,R相当于a(L)+1,a(R+1)-1
我们把端点 排好序之后,就直接跑一遍m
如果当前为左端点 则 覆盖层数++(意思就是 之后的每个数都多了一个区间覆盖)
如果当前为右端点 则覆盖层数--(意思就是 之后每个数都少了一个覆盖区间)
因为区间左闭右开,只要为奇数(灯亮),就加上左边右开区间 R-L的值
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
#include <math.h>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <math.h>
const int INF=0x3f3f3f3f;
typedef long long LL;
const int mod=1e9+;
const int maxn=1e7+;
using namespace std; struct node
{
int f;
int id;
bool friend operator < (node a,node b)
{
if(a.id==b.id)
return a.f<b.f;
return a.id<b.id;
}
}pos[]; int main()
{
int T;
scanf("%d",&T);
for(int k=;k<=T;k++)
{
int n,m;
int l,r;
int cnt=;
scanf("%d %d",&n,&m);
for(int i=;i<=m;i++)
{
scanf("%d %d",&l,&r);
pos[++cnt].id=l;
pos[cnt].f=;
pos[++cnt].id=r+;
pos[cnt].f=;
}
int cot=;
int ans=;
sort(pos+,pos++cnt);
for(int i=;i<=cnt-;i++)
{
if(pos[i].f)
cot--;
else
cot++;
if(cot%)
ans+=pos[i+].id-pos[i].id; }
printf("Case #%d: %d\n",k,ans);
}
return ;
}
最新文章
- 在window下配置laravel开发环境
- AngularJS ui-router (嵌套路由)
- 使用axes函数在matlab绘图中实现图中图的绘制
- 禁止苹果浏览器Safari将数字识别成电话号码的方法
- C++头文件为什么要加#ifndef #define #endif
- 广义线性模型 GLM
- inand和emmc区别
- 当前标识(NT AUTHORITY\NETWORK SERVICE)没有对“C:\WINDOWS2\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files”的写访问权限。
- C#调用Geocoding API进行地理编码与逆编码
- ASP读取RSS
- poj炮兵阵地(状压)(25+10+20=55)
- t-sql 中between and 的一种写法
- Mvvm绑定datagrid或listview的selectItems的方法[转]
- css初始化值
- html标签大全(1)
- js删除 object中的空值
- Adaptive Placeholders
- 模态框 modal data-toggle data-target
- 如何设计出优秀的Restful API?
- 产品排序(2015 年北大自招夏令营) (与栈相关的区间DP)
热门文章
- 基础语法-其它流程控制语句break和continue
- gcc/g++以c++11的方式编译
- SpringBoot的Banner横幅
- Yota Phone宣告破产
- html特殊字符的写法
- java向python ,text文件动态传参或传值问题完美解决
- grep 使用方法 --rn使用
- 吴裕雄--天生自然C++语言学习笔记:C++ 变量作用域
- Invalid bound statement (not found): com.xxxx.dao.other.LoginDao.getUser";
- 1.3 this深度面试题