1139 First Contact (30分)

巨坑。

注意点:

  1. 用负号表示女生,而不是负数表示女生,区别在一个特殊样例“-0000”
  2. 输出需用4位整数,不足4位用0补齐
#include<cstdio>
#include<vector>
#include<algorithm>
#include<iostream>
#include<string>

#define maxn 100000

using namespace std;
vector<int> g[maxn];  // graph
int gender[maxn] = {0};

struct friendsType {
    int f, s;  // first one and second one
};

int setgender(string str) {
    int a;
    sscanf(str.c_str(), "%d", &a);
    if (str[0] == '-') {
        a = -a;
        gender[a] = -1;
    }
    else gender[a] = 1;
    return a;
}

int delete_gender(int a) {
    if (a < 0) return -a;
    else return a;
}

bool compare(friendsType a, friendsType b) {
    if (a.f != b.f) {
        return a.f < b.f;
    }
    else return a.s < b.s;
}

vector<friendsType> findfirend(int a, int b) {
    vector<friendsType> fl;  // friend list
    int fa, fb;
    for (int i = 0; i < g[a].size(); i++) {
        fa = g[a][i];
        if (fa == b) continue;
        if (gender[fa] != gender[a]) continue;
        for (int j = 0; j < g[b].size(); j++) {
            fb = g[b][j];
            if (fb == a) continue;
            if (gender[fb] != gender[b]) continue;
            vector<int>::iterator it;
            for (it = g[fa].begin(); it != g[fa].end(); it++) {
                if (*it == fb) break;
            }
            if (it != g[fa].end()) {
                friendsType ftemp;
                ftemp.f = fa;
                ftemp.s = fb;
                fl.push_back(ftemp);
            }
        }
    }

    return fl;
}

int main () {
    int N, M, K;
    scanf("%d %d", &N, &M);
    int a, b;
    string stra, strb;
    while(M--) {
        cin >> stra >> strb;
        a = setgender(stra);
        b = setgender(strb);
        g[a].push_back(b);
        g[b].push_back(a);
    }
    scanf("%d", &K);
    while(K--) {
        scanf("%d %d", &a, &b);
        a = delete_gender(a);
        b = delete_gender(b);
        vector<friendsType> fl = findfirend(a, b);
        printf("%d\n", fl.size());
        sort(fl.begin(), fl.end(), compare);
        for (int i = 0; i < fl.size(); i++) {
            printf("%04d %04d\n", fl[i].f, fl[i].s);
        }
    }

    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值