OR101. 合并区间
描述
输入描述
一行整数,多个区间用空格隔开。区间的逗号是英文字符。输出描述
合并后的区间,用过空格隔开,行末无空格示例1
输入:
1,3 2,5
输出:
1,5
示例2
输入:
1,3 2,5 8,10 11,15
输出:
1,5 8,10 11,15
C 解法, 执行用时: 2ms, 内存消耗: 292KB, 提交时间: 2022-02-19
#include<stdio.h> #define MAXLEN 500 int main() { int n[MAXLEN] = {0}; int a,b; int flag = 0; while(scanf("%d,%d",&a,&b) != EOF) for(int i = a;i < b;i++) n[i] = 1; for(int i = 0;i < MAXLEN;i++) { if(n[i] && !flag) { printf("%d,",i); flag = 1; } if(!n[i] && flag) { printf("%d ",i); flag = 0; } } return 0; }
C++14 解法, 执行用时: 2ms, 内存消耗: 352KB, 提交时间: 2018-09-17
#include<iostream> #include<vector> #include <algorithm> using namespace std; int main() { int beg,end; char temp; vector<vector<int>> blocks_temp; while(cin>>beg>>temp>>end) { blocks_temp.push_back({beg,end}); } sort(blocks_temp.begin(), blocks_temp.end()); //for(int i=0;i<blocks_temp.size();i++) //{ //cout<<blocks_temp[i][0]<<','<<blocks_temp[i][1]<<" "; //} vector<vector<int>> blocks; blocks.push_back({blocks_temp[0][0],blocks_temp[0][1]}); int size=blocks_temp.size(); for(int i=1;i<size;i++) { if(blocks_temp[i][0]<=blocks[blocks.size()-1][1]) { blocks[blocks.size()-1][1]=max(blocks_temp[i][1],blocks[blocks.size()-1][1]); } else { blocks.push_back({blocks_temp[i][0],blocks_temp[i][1]}); } } for(int i=0;i<blocks.size();i++) { cout<<blocks[i][0]<<','<<blocks[i][1]<<" "; } return 0; }