【一本通】线段
- C语言代码
- Java代码
- C++代码
💐The Begin💐点点关注,收藏不迷路💐 |
数轴上有 n条线段,选取其中 k条线段使得这 k条线段两两没有重合部分,问最大的k为多少?
输入
输入文件segment.in的第一行为一个正整数 n;下面 n行每行有 2个数字ai,bi,描述每条线段。
输出
输出文件segment.out仅包括一个整数,为k的最大值。
样例输入
3
0 2
2 4
1 3
样例输出
2
C语言代码
#include <stdio.h>
#include <stdlib.h>
// 定义结构体来存储一组数据的两个属性
struct Data {
int first;
int second;
};
// 比较函数,用于qsort进行结构体数组按照second成员升序排序
int compare(const void *a, const void *b) {
struct Data *x = (struct Data *)a;
struct Data *y = (struct Data *)b;
return x->second - y->second;
}
int main() {
int num;
scanf(“%d”, &num);
struct Data *dataArr = (struct Data *)malloc(num * sizeof(struct Data));
if (dataArr == NULL) {
printf(“内存分配失败\n”);
return -1;
}
// 循环读取每组数据的两个属性值
for (int i = 0; i < num; i++) {
scanf(“%d %d”, &dataArr[i].first, &dataArr[i].second);
}
// 使用qsort对结构体数组进行排序
qsort(dataArr, num, sizeof(struct Data), compare);
int count = 1;
int prevSecond = dataArr[0].second;
for (int i = 1; i < num; i++) {
if (prevSecond <= dataArr[i].first) {
prevSecond = dataArr[i].second;
count++;
}
}
printf(“%d\n”, count);
free(dataArr);
return 0;
}
Java代码
import java.util.Arrays;
import java.util.Scanner;
class Data {
int first;
int second;
public Data(int first, int second) {
this.first = first;
this.second = second;
}
}
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int numElements = scanner.nextInt();
Data[] dataArray = new Data[numElements];
for (int i = 0; i < numElements; i++) {
int f = scanner.nextInt();
int s = scanner.nextInt();
dataArray[i] = new Data(f, s);
}
Arrays.sort(dataArray, (x, y) -> x.second - y.second);
int count = 1;
int prevSecond = dataArray[0].second;
for (int i = 1; i < numElements; i++) {
if (prevSecond <= dataArray[i].first) {
prevSecond = dataArray[i].second;
count++;
}
}
System.out.println(count);
}
}
C++代码
#include <iostream
>
#include <algorithm
>
using namespace std;
struct Data {
int first;
int second;
};
// 比较函数,用于按照结构体中second成员升序排序
bool compare(Data x, Data y) {
return x.second < y.second;
}
int main() {
int num;
cin >> num;
Data dataArr[num];
for (int i = 0; i < num; i++) {
cin >> dataArr[i].first >> dataArr[i].second;
}
sort(dataArr, dataArr + num, compare);
int result = 1;
int prevSecond = dataArr[0].second;
for (int i = 1; i < num; i++) {
if (prevSecond <= dataArr[i].first) {
prevSecond = dataArr[i].second;
result++;
}
}
cout << result << endl;
return 0;
}
💐The End💐点点关注,收藏不迷路💐 |