思路:从根节点开始BFS,找到最深的节点以及步数,然后从该节点开始进行第二次BFS,算出的步长就是最终的结果。
这里要注意的是,交换机和电脑标号要转化成1,2,3……的序列,得统一一下。还有数组G[n]要开大一些,开到20000+
#include <iostream> #include <vector> #include <queue> #include <cstring> using namespace std; #define MAX 20010 vector<int>G[MAX]; queue<int>q; bool visit[MAX]; int d[MAX]; int BFS(int s,int &p){ int ans = 0; memset(visit,0,sizeof(visit)); memset(d,0,sizeof(d)); p = s; while(!q.empty()) q.pop(); q.push(s); visit[s] = 1; while(!q.empty()){ int u = q.front(); q.pop(); for(int i=0;i<G[u].size();i++){ int v = G[u][i]; if(!visit[v]){ visit[v] = 1; d[v] = d[u] + 1; if(d[v] > ans){ ans = d[v]; p = v; } q.push(v); } } } return ans; } int main(){ int n,m,i,a; cin>>n>>m; for(i=2;i<=n;i++){ cin>>a; G[a].push_back(i); G[i].push_back(a); } for(i=1;i<=m;i++){ cin>>a; G[i+n].push_back(a); G[a].push_back(i+n); } int p; int ans = BFS(1,p); ans = BFS(p,p); cout<<ans<<endl; return 0; }
#include <iostream> #include <vector> #include <cstring> using namespace std; #define MAX 20010 vector<int>G[MAX]; bool visit[MAX]; int d[MAX]; int result; int s; void DFS(int u,int cost){ visit[u] = 1; if(result < cost){ result = cost; s = u; } for(int i=0;i<G[u].size();i++){ int v = G[u][i]; if(!visit[v]){ DFS(G[u][i],cost+1); } } } int main(){ int n,m,i,a; cin>>n>>m; for(i=2;i<=n;i++){ cin>>a; G[a].push_back(i); G[i].push_back(a); } for(i=1;i<=m;i++){ cin>>a; G[i+n].push_back(a); G[a].push_back(i+n); } result = -1; memset(visit,0,sizeof(visit)); DFS(1,0); result = -1; memset(visit,0,sizeof(visit)); DFS(s,0); //s是一次DFS之后最深的点 cout<<result<<endl; return 0; }