PAT甲级 1139 First Contact (30分)

终于写对了,发现自己错在哪里。假设题目给出的是1和4,让你找2和3,那么这个核心就是二重循环。
第一重循环找2,需要保证2不是4。
第二重循环找3,需要保证3不是1,就是漏了这个,后两个点才没过。
其他的,判断1和2有朋友关系了那么1就不是2,23,34同理。
然后我这是只看了算法笔记的写法,什么unordermap,stoi等等都不会就没用,用了两次的map映射,有点绕,不过思路比较简单,对应就是代码复杂,不过即使是只看了算法笔记的跨考生也能写出来。

#include <cstdio>
#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <algorithm>
using namespace std;
struct node{
    int id1, id2;
};
int n, m, k, G[310][310] = {}, total = 0, Hash[310] = {};
map<int, int> mp2;
bool cmp(node a, node b)
{
    if(mp2[a.id1] != mp2[b.id1]) return mp2[a.id1] < mp2[b.id1];
    else return mp2[a.id2] < mp2[b.id2];
}
int getnum(string &str)
{
    int sum = 0;
    for(int i = 0; i < str.size(); i++){
        if(str[i] != '-') sum = sum * 10 + str[i] - '0';
    }
    return sum;
}
int main()
{
    cin >> n >> m;
    string str1, str2;
    map<string, int> mp;
    for(int i = 0; i < m; i++){
        cin >> str1 >> str2;
        int t1 = getnum(str1), t2 = getnum(str2);
        if(mp.find(str1) == mp.end()) mp[str1] = total++;
        if(mp.find(str2) == mp.end()) mp[str2] = total++;
        mp2[mp[str1]] = t1, mp2[mp[str2]] = t2;
        G[mp[str1]][mp[str2]] = G[mp[str2]][mp[str1]] = 1;
        if(str1[0] != '-') Hash[mp[str1]] = 1;
        if(str2[0] != '-') Hash[mp[str2]] = 1;
    }
    cin >> k;
    for(int i = 0; i < k; i++){
        cin >> str1 >> str2;
        if(mp.find(str1) == mp.end() || mp.find(str2) == mp.end()) printf("0\n");
        else{
            int s1 = mp[str1], s2 = mp[str2];
            vector<node> rec;
            for(int i = 0; i < total; i++){
                if(G[s1][i] && Hash[s1] == Hash[i] && i != s2){
                    for(int j = 0; j < total; j++){
                        if(G[i][j] && G[j][s2] && Hash[j] == Hash[s2] && j != s1){
                            node temp;
                            temp.id1 = i, temp.id2 = j;
                            rec.push_back(temp);
                        }
                    }
                }
            }
            sort(rec.begin(), rec.end(), cmp);
            printf("%d\n", rec.size());
            for(int i = 0; i < rec.size(); i++){
                printf("%04d %04d\n", mp2[rec[i].id1], mp2[rec[i].id2]);
            }
        }
    }
    return 0;
}
发布了30 篇原创文章 · 获赞 0 · 访问量 383

猜你喜欢

转载自blog.csdn.net/qq_33942309/article/details/104330458