3049. Hosts排序

Master X

题干真有趣。
既然是IP地址
我为什么要用字符串……………………

10175102262 LarsPendragon

题干少一个条件:1≤n≤20

Li Dao

结构体排序,代码供参考

include

using namespace std;
int T;
struct Address
{
string IP,URL;
};
vector V;
int IPcmp(const string& aa,const string& bb)
{
stringstream s1(aa),s2(bb);
int a,b,c,d,x,y,z,p;
sscanf(aa.c_str(),”%d.%d.%d.%d”,&a,&b,&c,&d);
sscanf(bb.c_str(),”%d.%d.%d.%d”,&x,&y,&z,&p);
if(a!=x) return (a>n;
V.clear();
for(int i=1;i<=n;i++)
{
string a,b;
cin>>a>>b;
V.push_back((Address){a,b});
}
sort(V.begin(),V.end(),cmp);
for(int i=0;i<V.size();i++) cout<<V[i].IP<<” “<<V[i].URL<<endl;
return;
}

int main()
{
scanf(“%d”,&T);
for(int step=0;step<T;step++)
{
printf(“case #%d:\n”,step);
solve();
}
return 0;
}

Suzuki_Yuuta

直接把IP地址变成整数,再存到结构体里就完事了。

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

struct info {
    int ip[4];
    string url;
};

bool cmp(const info& A, const info& B) {
    if (A.ip[0] == B.ip[0]) {
        if (A.ip[1] == B.ip[1]) {
            if (A.ip[2] == B.ip[2]) {
                if (A.ip[3] == B.ip[3]) {
                    return (A.url < B.url);
                }
                return (A.ip[3] > B.ip[3]);
            }
            return (A.ip[2] > B.ip[2]);
        }
        return (A.ip[1] > B.ip[1]);
    }
    return (A.ip[0] > B.ip[0]);
}

void solve()
{
    int n; cin >> n; cin.ignore();
    info* data = new info[n];
    for (int i = 0; i < n; i++) {
        string sIP, sURL;
        cin >> sIP >> sURL;
        data[i].url = sURL;
        int temp = 0; int index = 0;
        for (int j = 0; j < sIP.length(); j++) {
            if (sIP[j] == '.' ) {
                data[i].ip[index] = temp; temp = 0; index++;
                continue;
            }
            temp *= 10; 
            temp += sIP[j] - '0';
            if (j + 1 == sIP.length()) {
                data[i].ip[index] = temp;
            }
        }
    }
    sort(data, data + n, cmp);
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < 4; j++) {
            cout << data[i].ip[j] << ((j + 1 == 4) ? " " : ".");
        }
        cout << data[i].url << endl;
    }
}

int main(int argc, char* argv[]) 
{
    int T; cin >> T; cin.ignore();
    for (int i = 0; i < T; i++) {
        cout << "case #" << i << ":" << endl;
        solve();
    }
    return 0;
}
你当前正在回复 博客/题目
存在问题!