poj 1089 区间问题 -- 水题一道
来源:互联网 发布:软件项目功能测试报告 编辑:程序博客网 时间:2024/06/16 09:33
/* * poj 1089 区间问题 题目大意: 数轴上n个区间,将有交叠的合并,最终按照升序输出各合并后的区间 解题思路: 题目很简单,算法也中规中矩 1、将各区间按照起始点从小到大排序 2、从前到后扫描相邻区间,如果有交叠则合并,否则视为下一个独立区间,同时输出上个独立区间*/#include <iostream>#include <cstdio>#include <cstdlib>namespace { using namespace std; const int N_MAX = 50000; typedef struct INTERVAL { int s, e; }INTERVAL_S; INTERVAL_S g_aIntervals[N_MAX]; // 读入区间数 // 区间数比较函数 int interval_cmp(const void *pOP1, const void *pOP2) { INTERVAL_S *pInterval1, *pInterval2; pInterval1 = (INTERVAL_S *)pOP1; pInterval2 = (INTERVAL_S *)pOP2; if (pInterval1->s < pInterval2->s) return -1; if (pInterval1->s == pInterval2->s) return 0; if (pInterval1->s > pInterval2->s) return 1; }}int main(){ int n; scanf("%d", &n); for (int i=0; i<n; i++) { scanf("%d %d", &g_aIntervals[i].s, &g_aIntervals[i].e); } // 以起点从小到大排序 qsort(g_aIntervals, n, sizeof(g_aIntervals[0]), interval_cmp); INTERVAL_S cur_interval; // 当前处理区间 // 从前向后线性扫描 int i = 0; while (i<n) { cur_interval = g_aIntervals[i]; // 一个区间的处理 int j = i+1; while (j<n && g_aIntervals[j].s<=cur_interval.e) { if (g_aIntervals[j].e > cur_interval.e) cur_interval.e = g_aIntervals[j].e; ++j; } // 打印之 printf("%d %d\n", cur_interval.s, cur_interval.e); i = j; } return 0;}