A1139
Description:
若A要追B,则要找到同性好友C,委托C找到B的同性好友,现给出朋友关系,求出符合题意的朋友序列;
思路:
- 第一遍做的时候用的字符串接收ID,第二遍做的时候注意到题目描述为"4-digit ID",专门看了一下digit的释义,是0-9的数字的意思,于是考虑用int接收ID,结果测试点2始终过不去,看了柳神的解释,-0000和0000无法判断性别,好吧换回字符串AC了,注意深搜策略;
- 代码没什么可看的,写得又臭又长;
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>
#include<map>
#include<unordered_map>
#include<vector>
#include<queue>
using namespace std;
const int maxn = 305;
struct Peo{
string name;
vector<int>fri;
}peo[maxn];
bool mp[maxn][maxn];
unordered_map<string,int>getIndex;
int n, m, in = 1;
int getIn(string &a){
if(getIndex[a]==0){
peo[in].name = a;
getIndex[a] = in;
return in++;
}
return getIndex[a];
}
struct node{
string fir, sec;
};
vector<node>ans;
bool cmp(node &a, node &b){
if(a.fir == b.fir) return a.sec < b.sec;
return a.fir < b.fir;
}
bool isBoy(string &n){
if(n[0] == '-') return false;
return true;
}
void dfs(string now, string d, int t, string pre){
int nowIn = getIn(now);
int len = peo[nowIn].fri.size();
for(int i = 0; i < len; i++){
int fir = peo[nowIn].fri[i];
if(t == 1 && isBoy(now)==isBoy(peo[fir].name) && peo[fir].name!=d && peo[fir].name!=now){
dfs(peo[fir].name, d, t+1, now);
}else if(t == 2 && isBoy(d)==isBoy(peo[fir].name) && peo[fir].name!=d && peo[fir].name!=pre){
if(mp[getIn(peo[fir].name)][getIn(d)])ans.push_back(node{now,peo[fir].name});
}
}
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("1.txt", "r", stdin);
#endif // ONLINE_JUDGE
scanf("%d%d", &n, &m);
string a, b;
memset(mp, false, sizeof(mp));
for(int i = 0; i < m; i++){
cin>>a>>b;
int ain = getIn(a);
int bin = getIn(b);
peo[ain].fri.push_back(bin);
peo[bin].fri.push_back(ain);
mp[ain][bin] = true;
mp[bin][ain] = true;
}
int k;
scanf("%d", &k);
for(int i = 0; i < k; i++){
ans.clear();
cin>>a>>b;
if(getIndex[a]==0||getIndex[b]==0){
printf("0\n");
continue;
}
dfs(a, b, 1, "");
printf("%d\n", ans.size());
sort(ans.begin(), ans.end(), cmp);
int len = ans.size();
for(int j = 0; j < len; j++){
if(ans[j].fir[0] == '-') printf("%s", ans[j].fir.substr(1, 4).c_str());
else printf("%s", ans[j].fir.c_str());
if(ans[j].sec[0] == '-') printf(" %s\n", ans[j].sec.substr(1, 4).c_str());
else printf(" %s\n", ans[j].sec.c_str());
}
}
return 0;
}