【百度之星】-IP聚合
问题描述:
问题分析:
使用map,哈希一下结果就好了。原来将int -> string 来存network address 发现 TLE了,后来改成直接存Long long 187ms过了。结论就是: 库函数中,int 转 string的方法是在是太慢了。
代码如下:
#include <iostream> #include <cstdio> #include <string> #include <math.h> #include <map> #include <algorithm> #include <sstream> #define LL __int64 #define MOD 1000000007 using namespace std; const int MAXN = 1001; int n; LL IP[MAXN][4], Mask[4], netAddress; map<LL, int>strHashMp; template<class T> void toString(string & result, const T& t) { ostringstream oss; oss << t; result = oss.str(); } int main() { int T, cas = 0, n,m; cin>>T; while(T--){ scanf("%d%d",&n,&m); for(int i = 0; i < n; i ++) scanf("%d.%d.%d.%d",&IP[i][0],&IP[i][1],&IP[i][2],&IP[i][3]); printf("Case #%d:\n",++cas); for(int i = 0; i < m; i ++){ scanf("%I64d.%I64d.%I64d.%I64d",&Mask[0],&Mask[1],&Mask[2],&Mask[3]); strHashMp.clear(); int ans = 0; for(int j = 0; j < n ; j ++){ string strAdd = ""; netAddress = 0; for(int k = 0; k < 4; k ++){ LL andVal = Mask[k] & IP[j][k]; netAddress = netAddress * 1000 + andVal; } if(strHashMp.find(netAddress) == strHashMp.end()){ ans ++; strHashMp[netAddress] = 1; } } printf("%d\n", ans); } }//system("pause"); return 0; }