一个<时间,ip>列表,求时间Y秒内ip出现次数超过指定数M的ip的列表
这里我把题目提升为求出最小的M个数...就相当于从第1s开始到M秒,注意这里没秒对应一个ip...这些题都是只言片语也不知道是不是百度的题,反正可以肯定的是最近爱上了heap和tree什么算法都喜欢用这两个东东实现
#include <stdio.h> #include <stdlib.h>
#define M 10
static int count = 0; typedef struct IP { int second; char ip[16]; }IP;
typedef struct tree { IP* ipaddress; struct tree* parent; struct tree* lchild; struct tree* rchild; }TREE; int add_tree(TREE** T,TREE* parent,IP* ipaddress) { if(*T == NULL) { *T = (TREE*)malloc(sizeof(TREE)); (*T)->ipaddress = ipaddress; (*T)->parent = parent; (*T)->lchild = NULL; (*T)->rchild = NULL; return 0; } else if((*T)->ipaddress->second > ipaddress->second) return add_tree(&((*T)->lchild),*T,ipaddress); else return add_tree(&((*T)->rchild),*T,ipaddress); }
int tree_walk(TREE* T) { if(T==NULL) return 0; tree_walk(T->lchild); if( ++count<=M ) printf("%d\t",T->ipaddress->second); else return 0; tree_walk(T->rchild); }
int main(int argc, char *argv[]) { int i = 0; IP* I[23]; TREE* T = NULL; for(;i<23;i++) { I[i] = (IP*)malloc(sizeof(IP)); if(i==0) { I[i]->second = 30; printf("second is %d\n",I[i]->second); sprintf(I[i]->ip,"192.168.10.%d",30); } else if(i<12) { I[i]->second = i+9; sprintf(I[i]->ip,"192.168.10.%d",i+9); } else { I[i]->second = i+28; sprintf(I[i]->ip,"192.168.10.%d",i+28); } }
for(i=0;i<23;i++) add_tree(&T, NULL, I[i]); tree_walk(T); system("PAUSE"); return 0; }
|
阅读(1146) | 评论(0) | 转发(0) |