https://pintia.cn/problem-sets/994805342720868352/problems/994805344776077312
难倒是不难,但是有坑,例如-0000,0000
故我们还是得用字符串来读入。
这里的话需要离散化一下,将字符串映射到一个值,这样的话可以直接用邻接矩阵来存边。
#include<bits/stdc++.h>
using namespace std;
vector<int>boys,girls;
unordered_map<string,int>hush;
unordered_map<int,string>val;//通过值找到原始的值。
int n,m,k,idx;
int g[1005][1005];
int get(string x)
{
if(hush.count(x)==0) hush[x]=++idx;
val[hush[x]]=x;
return hush[x];
}
void solve(string a,string b)
{
vector<int>ve1,ve2;
vector<pair<int,int>>ans;
if(a.size()==5) ve1=girls;
else ve1=boys;
if(b.size()==5) ve2=girls;
else ve2=boys;
int a1=get(a),b1=get(b);
for(int i=0;i<ve1.size();i++)//暴力枚举
{
for(int j=0;j<ve2.size();j++)
{
int x=ve1[i],y=ve2[j];
if(x==a1||x==b1||y==a1||y==b1) continue;
if(g[a1][x]&&g[x][y]&&g[y][b1])
ans.push_back({
abs(stoi(val[x])),abs(stoi(val[y]))});
}
}
cout<<ans.size()<<endl;
sort(ans.begin(),ans.end());
for(int i=0;i<ans.size();i++)
printf("%04d %04d\n",ans[i].first,ans[i].second);
}
int main(void)
{
cin>>n>>m;
for(int i=0;i<m;i++)
{
string a,b; cin>>a>>b;
int x=get(a),y=get(b);
g[x][y]=g[y][x]=1;
if(a.size()==4) boys.push_back(x);
else girls.push_back(x);
if(b.size()==4) boys.push_back(y);
else girls.push_back(y);
}
sort(boys.begin(),boys.end());
boys.erase(unique(boys.begin(), boys.end()), boys.end());//去重
sort(girls.begin(),girls.end());
girls.erase(unique(girls.begin(), girls.end()), girls.end()); //去重
cin>>k;
while(k--)
{
string a,b; cin>>a>>b;
solve(a,b);
}
return 0;
}