【问题描述】
为了提高文章质量,每一篇文章(假设全部都是英文)都会有m名编辑审核,每个编辑独立工作,会把觉得有问题的句子通过下标记录下来,比如[1,10],1表示病句的第一个字符,10表示病句的最后一个字符。也就是从1到10个字符组成的句子,是有问题的。
现在需要把多名编辑有问题的句子合并起来,送给总编辑进行最终的审核。比如编辑a指出的病句是[1,10],[32,45];b编辑指出的病句是[5,16],[78,94],那么[1,10]和[5,16]是有交叉的,可以合并成[1,16],[32,45],[78,94]
【输入】
编辑数量m,之后每行是每个编辑的标记的下标集合,第一个和最后一个下标用英文逗号分隔,每组下标之间用分号分隔。
【输出】
合并后的下标集合,第一个和最后一个下标用英文逗号分隔,每组下标之间用分号分隔。返回结果是从小到大的递增排列。
题解:一道贪心题,按start下标排序,之后定义now1,now2两个变量,就OK了
详情请见代码:
#include<iostream> #include<cstdio> #include<cstring> #include<cstdlib> #include<cmath> #include<algorithm> using namespace std; struct Wr { int st; int en; }; Wr q[1000010]; bool cmp(Wr a,Wr b) { return a.st<b.st; } int k; int max_s=-1; int main() { //freopen("sentence.in","r",stdin); //freopen("sentence.out","w",stdout); int n; cin>>n; for(int i=1;i<=n;i++) { char a[100001]; scanf("%s",a); int la=strlen(a); int x=0; bool flag2=1; int s; for(int i=0;i<la;i++) { if(a[i]>='0' && a[i]<='9') { x=x*10+a[i]-'0'; } else { if(x>max_s) max_s=x; if(flag2) s=x; else { q[++k].st=s; q[k].en=x; } flag2=!flag2; x=0; } } } sort(q+1,q+k+1,cmp); bool flag=0; int now1,now2; now1=q[1].st; now2=q[1].en; for(int i=2;i<=k;i++) { if(q[i].st<=now2) now2=max(q[i].en,now2); else { if(!flag) { printf("%d,%d",now1,now2); flag=1; } else { printf(";%d,%d",now1,now2); } now1=q[i].st; now2=q[i].en; } } if(!flag) { printf("%d,%d",now1,now2); } else { printf(";%d,%d",now1,now2); } return 0; }