#include <algorithm>
#include <iostream>
using namespace std;
typedef struct _node {
int s;
int e;
} Node;
bool cmp(Node p, Node q) {
if (p.s == q.s)
return p.e < q.e;
return p.s < q.s;
}
Node d[10000]; // 10000個Node,用於儲存線段的兩個端點座標
int main() {
int N; //幾個線段
while (cin >> N) {
for (int i = 0; i < N; i++) {
cin >> d[i].s >> d[i].e;
}
for(int i=0; i<N; i++){
if(d[i].s > d[i].e){
int tmp = d[i].s;
d[i].s = d[i].e;
d[i].e = tmp;
}
}
//已將線段頭由小排到大,若頭相等,則由尾由小排到大
sort(d, d + N, cmp);
int length = 0; //總長度
int s, e;
for (int i = 0; i < N; i++) {
s = d[i].s;
e = d[i].e;
while ((s <= d[i + 1 ].s) && (e >= d[i + 1].s)) { //是否有覆蓋到下一個線段
if (d[i + 1].e < e) { //覆蓋到下一段的全部
i++;
} else {
e = d[i+1].e;
i++;
}
}
length += (e - s);
}
cout << length;
}
}
卡在測資53 segmentation fault (core dumped)
哪邊有問題嗎QQ