IP段去重
来源:互联网 发布:starbound知乎 编辑:程序博客网 时间:2024/05/19 06:46
原文
下面的代码是从网上拷贝的,经过了一番学习研究后觉得写的比较好,就挂上来,也留作以后工作所用
这段代码的思想也是先排序,然后去重的
#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 intcmpNodep(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
0 0
- IP段去重
- IP
- IP
- ip
- IP
- IP
- ip
- IP
- IP
- IP
- ip
- ip
- IP
- ip
- ip
- IP
- IP
- IP
- Silverlight实现类似Mac Dock特效
- text框中按enter触发js事件
- 关于c++中const
- 计算机“速成”之法
- 【算法】 擅长排列的小明
- IP段去重
- IO中同步、异步与阻塞、非阻塞的区别
- mysql恢复和备份数据库中的表
- java开发_生成/解析自己的QRCode二维码
- 大话重构
- 使用storyboard实现页面跳转,简单的数据传递
- Thread 1 cannot allocate new log
- 关于android百度地图离线地图的使用
- 网站发展移动端选择App or HTML5?