下面的代码是从网上拷贝的,经过了一番学习研究后觉得写的比较好,就挂上来,也留作以后工作所用
这段代码的思想也是先排序,然后去重的
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
unsigned int start;
unsigned int end;
} Node;
void print_out(unsigned int start_pos, unsigned int end_pos)
{
printf("%u.%u.%u.%u ", start_pos >> 24,
start_pos >> 16 & 0xFF,
start_pos >> 8 & 0xFF,
start_pos & 0xFF);
printf("%u.%u.%u.%u\n", end_pos >> 24,
end_pos >> 16 & 0xFF,
end_pos >> 8 & 0xFF,
end_pos & 0xFF);
return;
}
static int
cmpNodep(const void *p1, const void *p2)
{
if (((Node *)p1)->start > ((Node *)p2)->start)
return 1;
if (((Node *)p1)->start < ((Node *)p2)->start)
return -1;
return (((Node *)p1)->end - ((Node *)p2)->end);
}
int main()
{
unsigned int start_pos, end_pos;
unsigned int i, tmp;
int start[4], end[4];
Node node_array[3000];
int node_array_size;
node_array_size = 0;
while (1)
{
if (scanf("%u.%u.%u.%u %u.%u.%u.%u", &start[0], &start[1], &start[2], &start[3],
&end[0], &end[1], &end[2], &end[3]) <= 0)
break;
start_pos = start[0]*256*256*256 + start[1]*256*256 + start[2]*256 + start[3];
end_pos = end[0]*256*256*256 + end[1]*256*256 + end[2]*256 + end[3];
node_array[node_array_size].start = start_pos;
node_array[node_array_size].end = end_pos;
node_array_size++;
}
qsort(node_array, node_array_size, sizeof(Node), cmpNodep);
start_pos = node_array[0].start;
end_pos = node_array[0].end;
for (i=1; i<node_array_size; i++)
{
// If next start before current end (+1 for merge),
// update the new end if necessary
if (node_array[i].start <= end_pos + 1)
{
if (node_array[i].end > end_pos)
end_pos = node_array[i].end;
}
else
{
// If next start after current end,
// print this section and start new one
print_out(start_pos, end_pos);
start_pos = node_array[i].start;
end_pos = node_array[i].end;
}
}
print_out(start_pos, end_pos);
return 0;
}
输入:
1.1.1.1 2.2.2.2
3.3.3.3 4.4.4.4
1.1.1.1 2.2.2.9
3.3.3.8 4.4.4.9
sdf
结果:
1.1.1.1 2.2.2.9
3.3.3.3 4.4.4.9