百度之星打个酱油,结果发现自己真是太菜。。嗯,记录一下这个题,算法很挫,暴力法解决,不过里面的字符串分割记录一下吧,备忘。
Code
#include<iostream> #include<string> #include<sstream> #include<algorithm> using namespace std; string* split(string str,string pattern) { string::size_type pos; string* result = new string[4]; str += pattern; int size = str.size(); int n = 0; for(int i = 0; i < size; i++) { pos = str.find(pattern,i); if(pos < size) { string s = str.substr(i,pos-i); //result.push_back(s); result[n++] = s; i = pos+pattern.size()-1; } } return result; } int main() { int T; int n,m; string *ip = new string[1000]; string *address = new string[1000]; string *mask = new string[50]; char *temp = new char[10]; int same_mask_num[50]; int mask_len,ip_len; //vector<string> str_mask_list; string *str_mask_list;// = new string[4]; string *str_ip_list;// = new string[4]; //vector<string> str_ip_list; char *ip_str,*mask_str; cin >> T; int i,j,k; for(i = 0; i < T; ++i) { cin >> n >> m; for(ip_len = 0; ip_len < n; ++ip_len) { cin >> ip[ip_len]; } for(mask_len = 0; mask_len < m; ++mask_len) { same_mask_num[mask_len] = 1; cin >> mask[mask_len]; str_mask_list = split(mask[mask_len],"."); for(j = 0; j < ip_len; ++j) { address[j] = ""; str_ip_list = split(ip[j],"."); for(k = 0; k < 4; ++k) { ip_str = const_cast<char*>(str_ip_list[k].c_str()); mask_str = const_cast<char*>(str_mask_list[k].c_str()); sprintf(temp,"%d.",atoi(ip_str)&atoi(mask_str));//itoa( atoi(ip_str)&atoi(mask_str),temp,10); address[j] += temp; //address[j] +='.'; } } sort(address,address+ip_len); for(j = 0; j < ip_len-1; ++j) { if(address[j] != address[j+1]) same_mask_num[mask_len]++; } } cout << "Case #" << i+1 << ":" << endl; for(k = 0; k < mask_len;++k) cout << same_mask_num[k] << endl; } return 0; }原文链接:https://www.f2er.com/javaschema/284741.html