JustAdieu @ 2024-12-12 19:29:19
#include<stdio.h>
#include<stdlib.h>
#ifndef TREE_H
#define TREE_H
typedef struct TreeNode {
int value[2];
struct TreeNode* left;
struct TreeNode* right;
}TreeNode;
TreeNode* creatNode(int value[2]);
void insertNode(TreeNode** root, int value[2]);
void freeTree(TreeNode* root);
void countTree(TreeNode* root,int *count);
#endif
TreeNode* creatNode(int value[2]) {
TreeNode* newnode = (TreeNode*)malloc(sizeof(TreeNode));
if (newnode == NULL) {
printf("Memory allocation error\n");
exit(1);
}
else {
newnode->value[0] = value[0];
newnode->value[1] = value[1];
newnode->left = NULL;
newnode->right = NULL;
}
return newnode;
}
void insertNode(TreeNode** root, int value[2]) {
if (*root == NULL) {
*root = creatNode(value);
}
else {
if ((*root)->value[0] > value[1]) {//不重叠区间位于原有区间左边
insertNode(&((*root)->left), value);
}
else if ((*root)->value[1] < value[0]) {//不重叠区间位于原有区间右边
insertNode(&((*root)->right), value);
}
else if ((*root)->value[0]<=value[0]&&(*root)->value[1]>=value[1]) {//重叠区间位于区间里面
}
else if ((*root)->value[0]>=value[0] && (*root)->value[1]<=value[1]) {//重叠区间位于区间外面
(*root)->value[0] = value[0];
(*root)->value[1] = value[1];
}
else if ((*root)->value[0]<=value[1]&& (*root)->value[1]>=value[1]) {//重叠区间位于原有区间左边
(*root)->value[0] = value[0];
}
else if ((*root)->value[0]<=value[0] && (*root)->value[1]>=value[0]) {//重叠区间位于原有区间右边
(*root)->value[1] = value[1];
}
else {
printf("error!!!\n");
exit(1);
}
}
}
void freeTree(TreeNode* root) {
if (root != NULL) {
freeTree(root->left);
freeTree(root->right);
free(root);
}
}
void countTree(TreeNode* root,int *count) {
if (root != NULL) {
*count += (root->value[1] - root->value[0] + 1);
countTree(root->left, count);
countTree(root->right, count);
}
}
int main() {
int number, area,count=0;
scanf("%d %d", &number, &area);
getchar();
TreeNode* root = NULL;
int (*value)[2] = malloc(area * sizeof(int[2]));
if (value == NULL) {
fprintf(stderr, "Memory allocation error\n");
exit(1);
}
for (int i = 0; i < area; i++) {
scanf("%d %d",&value[i][0],&value[i][1]);
getchar();
insertNode(&root, value[i]);
}
countTree(root, &count);
count = number + 1 - count;
printf("%d", count);
freeTree(root);
free(value);
return 0;
}
by YXC20142024 @ 2024-12-13 19:23:01
用我代码
include <iostream>
using namespace std;
int main()
{
int a[10010],b,c,d,e,f=0;
cin>>b>>c;
for(int i=0;i<=b;i++)
{
a[i]=1;
}
for(int j=0;j<=c-1;j++)
{
cin>>d>>e;
for(int k=d;k<=e;k++)
{
a[k]=0;
}
}
for(int l=0;l<=b;l++)
{
if (a[l]==1)
f++;
}
cout<<f;
return 0;
}
by YXC20142024 @ 2024-12-13 19:27:46
哈哈
by YXC20142024 @ 2024-12-13 19:29:51
第83行
by Infinite_Eternitt @ 2024-12-19 23:13:44
没必要这么麻烦,20行就解决的题目为何要整这么多行の代码??(83行大大的问题)
#include<bits/stdc++.h>
using namespace std;
int tree[100005];
int main(){
int a,b;
cin>>a>>b;
for(int i=1;i<=b;i++){
int c,d;
cin>>c>>d;
for(int i=c;i<=d;i++){
tree[i]=1;
}
}
int ans=0;
for(int i=0;i<=a;i++){
if(tree[i]==0){
ans++;
}
}
cout<<ans;
return 0;
}