【题目来源】
https://www.luogu.com.cn/problem/P1496
【题目背景】
曹操平定北方以后,公元 208 年,率领大军南下,进攻刘表。他的人马还没有到荆州,刘表已经病死。他的儿子刘琮听到曹军声势浩大,吓破了胆,先派人求降了。
孙权任命周瑜为都督,拨给他三万水军,叫他同刘备协力抵抗曹操。
隆冬的十一月,天气突然回暖,刮起了东南风。
没想到东吴船队离开北岸大约二里距离,前面十条大船突然同时起火。火借风势,风助火威。十条火船,好比十条火龙一样,闯进曹军水寨。那里的船舰,都挤在一起,又躲不开,很快地都烧起来。一眨眼工夫,已经烧成一片火海。
曹操气急败坏的把你找来,要你钻入火海把连环线上着火的船只的长度统计出来!
【题目描述】
给定每个起火部分的起点和终点,请你求出燃烧位置的长度之和。
【输入格式】
第一行一个整数,表示起火的信息条数 n。
接下来 n 行,每行两个整数 a,b,表示一个着火位置的起点和终点(注意:左闭右开)。
【输出格式】
输出一行一个整数表示答案。
【数据规模与约定】
对于全部的测试点,保证 1≤n≤2×10^4,−2^31≤a<b<2^31,且答案小于 2^31。
【输入样例】
3
-1 1
5 11
2 9
【输出样例】
11
【算法分析】
● 按结构体某一字段对结构体数组进行排序:https://blog.csdn.net/hnjzsyjyj/article/details/120184972
● 区间合并模板题(AcWing 803:区间合并)代码:https://blog.csdn.net/hnjzsyjyj/article/details/145067059
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
struct Section {
int x;
int y;
} a[maxn];
bool cmp(Section u,Section v) {
if(u.x==v.x) return u.y<v.y;
return u.x<v.x;
}
int main() {
int n;
cin>>n;
for(int i=1; i<=n; i++) {
cin>>a[i].x>>a[i].y;
}
sort(a+1,a+1+n,cmp);
int base=a[1].y;
int cnt=1;
for(int i=1; i<=n; i++) {
if(a[i].x<=base) base=max(base,a[i].y);
else cnt++,base=a[i].y;
}
cout<<cnt<<endl;
return 0;
}
/*
in:
10
-15 -8
-20 23
-2 11
2 22
18 23
11 27
-8 21
-18 14
-17 -12
-23 8
out:
1
*/
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int maxn=2e5;
struct Point {
int x;
int y;
} a[maxn];
bool cmp(Point u,Point v) {
if(u.x==v.x) return u.y<v.y;
return u.x<v.x;
}
int main() {
int n;
cin>>n;
for(int i=1; i<=n; i++) {
cin>>a[i].x>>a[i].y;
}
sort(a+1,a+1+n,cmp);
int cnt=0;
int from=a[1].x;
int base=a[1].y;
for(int i=1; i<=n; i++) {
if(a[i].x<=base) base=max(base,a[i].y);
else {
cnt+=(base-from);
from=a[i].x;
base=a[i].y;
}
}
cnt+=(base-from);
cout<<cnt<<endl;
return 0;
}
/*
in:
3
-1 1
5 11
2 9
out:
11
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/120184972
https://blog.csdn.net/hnjzsyjyj/article/details/145067059