PTA | 程序设计类实验辅助教学平台
题解:
bfs可以求解从根节点到叶子节点的指定路径,这里的vis[]不是为了防止访问到父节点,更多的是为了缩小路径长度,mpp和mp的映射也很巧妙,开始我用的还是map<pair<string,string,int>,差点没麻烦死
#include<bits/stdc++.h>
using namespace std;
const int N=1e4+10;
bool vis[N];//虽然是有向图,但是必要
int n,idx;
vector<int>p[N];
map<string,int>mp;
map<int,string>mpp;
int pre[N];//记录路径
vector<int>bfs(int s,int e)
{
pre[e]=-1;
queue<int>q;
q.push(s);
memset(vis,0,sizeof vis);
vis[s]=1;
while(q.size())
{
int x=q.front();
if(x==e)break;
q.pop();
for(int i=0;i<p[x].size();i++)
{
if(vis[p[x][i]])continue;
vis[p[x][i]]=1;
q.push(p[x][i]);
pre[p[x][i]]=x;
}
}
vector<int>t;
if(pre[e]==-1)return t;
while(e!=s)
{
t.push_back(e);
e=pre[e];
}
t.push_back(s);
reverse(t.begin(),t.end());
return t;
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
{
string s1,s2,id1,id2;
cin>>s1>>id1>>s2>>id2;
if(mp.count(s1+" 0")==0)
{
mpp[idx]=s1+" 0";
mp[s1+" 0"]=idx++;
mpp[idx]=s1+" 1";
mp[s1+" 1"]=idx++;
}
if(mp.count(s2+" 0")==0)
{
mpp[idx]=s2+" 0";
mp[s2+" 0"]=idx++;
mpp[idx]=s2+" 1";
mp[s2+" 1"]=idx++;
}
s1+=" "+id1;
s2+=" "+id2;
p[mp[s1]].push_back(mp[s2]);
}
vector<int>ans(2020)//定义了一个容量为2020的vector,且里面每个值为0;
for(int i=0;i<idx;i+=2)
{
vector<int>s1=bfs(i,i+1);
vector<int>s2=bfs(i+1,i);
if(ans.size()>s1.size()&&s1.size()>0)
{
ans=s1;
}
if(ans.size()>s2.size()&&s2.size()>0)
{
ans=s2;
}
}
for(int i=0;i<ans.size()-1;i++)
cout<<mpp[ans[i]]<<" "<<mpp[ans[i+1]]<<" ";
cout<<"= ";
cout<<mpp[ans[0]]<<" "<<mpp[ans[ans.size()-1]];
return 0;
}