CIDR去重-滴滴笔试题

题目链接

  • https://www.nowcoder.com/questionTerminal/6d76dfaf92cf478b93b60dd277b94ffa?toCommentId=1871859

思路和考点

  • 这道题主要是对字符串进行分割,解析,然后将ip逆序保存,判断位数较少的是否被位数较多的数包围。思路比较简单,就是实现比较麻烦。

代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
typedef unsigned char uchar;

//#define G_DEBUG

uchar reverseBits(uchar n) {
    n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1);
    n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2);
    n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4);
    return n;
}

int main()
{

#ifdef G_DEBUG
    // 调试使用
    int N = 0;
    ifstream file("data.txt");

    string s;
    getline( file, s );
    N = atoi( s.c_str() );
    vector strs(N);
    int i = 0;
    while( getline( file, s ))
        strs[i++] = s;
#else
    int N = 0;
    cin >> N;
    vector strs(N);

    for (int i = 0; i < N; i++)
        cin >> strs[i];

#endif

    vector bit_nums(N, 0);
    vector val_nums(N, 0);
    int idx = 0;
    int curr_bit = 0;
    ll curr_val = 0;
    ll tmp = 0;
    ll tmp_val = 0;
    uchar c;
    for (int i = 0; i < N; i++)
    {
        idx = strs[i].find_first_of('/');
        bit_nums[i] = atoll(strs[i].substr(idx + 1).c_str());

        idx = strs[i].find_first_of('.');
        c = atoi(strs[i].substr(0, idx).c_str());
        curr_val = (ll)reverseBits(c);
        tmp = idx;

        idx = strs[i].find_first_of('.', idx + 1);
        c = atoi(strs[i].substr(tmp + 1, idx - tmp).c_str());
        curr_val = ((ll)reverseBits(c) << 8) | curr_val;
        tmp = idx;

        idx = strs[i].find_first_of('.', idx + 1);
        c = atoi(strs[i].substr(tmp + 1, idx - tmp).c_str());
        curr_val = ((ll)reverseBits(c) << 16) | curr_val;
        tmp = idx;

        idx = strs[i].find_first_of('.', idx + 1);
        c = atoi(strs[i].substr(tmp + 1, idx - tmp).c_str());
        curr_val = ((ll)reverseBits(c) << 24) | curr_val;

        curr_val = (((ll)1 << bit_nums[i]) - 1) & curr_val;

        val_nums[i] = curr_val;
    }

    vector removed_idxs;
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
        {
            if (i == j)
                continue;
            if ((bit_nums[i] >= bit_nums[j] )
                && (val_nums[j] == (val_nums[i] & (((ll)1 << bit_nums[j]) - 1)))
                )
            {
                removed_idxs.push_back( i );
                break;
            }
        }
    }

    int re_idx = 0;
    cout << (N - removed_idxs.size()) << endl;
    for (int i = 0; i < N; i++)
    {
        if (removed_idxs.size() > re_idx && i == removed_idxs[re_idx])
        {
            re_idx++;
            continue;
        }
        cout << strs[i] << endl;
    }


    system("pause");
    return 0;
}

你可能感兴趣的:(刷题,算法导论)