PAT 甲级 1139 First Contact (30 分) map+vector

题意:

A,C是同性,,,B,D 是异性  ,,

现在A看上了B,要给B写信,但是不能直接给B,

然后找到了同性的朋友C,让C给C的朋友D,

再由D转交给B,,这时候D也得是B的朋友

给定A和B,问这样的C,D有多少,并输出

 

思路:

朋友关系用邻接表储存,

每个人的同性别的朋友用vector存起来

然后每次分别遍历A,B的同性别朋友c,d,,,然后判断c,d是不是朋友关系,是的话就符合C,D,存起来

 

注意:若遍历A的同性朋友的时候,找到了B要跳过,因为他们不行直接相互传递

 

#include<bits/stdc++.h>
#include<cstring>
#define FI first
#define SE second

using namespace std;
typedef long long ll;
typedef pair<string, string> P;
const int maxn = 300 + 77;

int n, m, q, id = 1;
map<string, int> mp;
string u, v;

vector<string> vec[maxn];
bool d[maxn][maxn];

bool cmp(P a, P b) {
    return (a.FI == b.FI ? a.SE < b.SE : a.FI < b.FI);
}
vector<P> ans;
void solve() {
    ans.clear();
    cin >> u >> v;
    int t1 = mp[u], t2 = mp[v];
    if(!t1 || !t2) {
        cout << 0 << endl;
        return;
    }
    string x, y;
    for(auto i : vec[t1]) {
        int t3 = mp[i];
        if(t3 == t2) continue;
        if(i[0] == '-') x = i.substr(1, 4);
        else x = i.substr(0, 4);
        for(auto j : vec[t2]) {
            int t4 = mp[j];
            if(t4 == t1) continue;
            if(d[t3][t4]) {
                if(j[0] == '-') y = j.substr(1, 4);
                else y = j.substr(0, 4);
                ans.push_back(P(x, y));
            }
        }
    }
    cout << ans.size() << endl;
    sort(ans.begin(), ans.end(), cmp);
    for(auto k : ans) {
        cout << k.FI << " " << k.SE << endl;
    }
    return;
}
int main() {
    cin >> n >> m;
    for(int i = 1; i <= m; ++i) {
        cin >> u >> v;
        if(!mp[u]) mp[u] = id++; int t1 = mp[u];
        if(!mp[v]) mp[v] = id++; int t2 = mp[v];
        if(u.size() == v.size()) {
            vec[t1].push_back(v);
            vec[t2].push_back(u);
        }
        d[t1][t2] = d[t2][t1] = 1;
    }
    cin >> q;
    for(int i = 1; i <= q; ++i) {
        solve();
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值