Problem A. Planet Distance
题目传送门:https://code.google.com/codejam/contest/4384486/dashboard#s=p0
我的做法是先用Kahn算法找出环中所有结点。然后用一遍BFS计算所有点到环的最近距离。
参考代码:
int main()
{
int no;
cin>>no;
for (int nn=1;nn<=no;nn++){
int n,a,b;
cin>>n;
vector<vector<int>> edge(n);
vector<int> degree(n);
vector<bool> live(n,true);
vector<int> dist(n);
for (int i=0;i<n;i++){
cin>>a>>b;
edge[a-1].push_back(b-1);
degree[b-1]++;
edge[b-1].push_back(a-1);
degree[a-1]++;
}
//find the circle
queue<int> q;
for (int i=0;i<n;i++)
if (degree[i]==1)
q.push(i);
while (!q.empty()){
int cur=q.front();
q.pop();
live[cur]=false;
degree[cur]--;
for (int i=0;i<edge[cur].size();i++)
if (live[edge[cur][i]] && (--degree[edge[cur][i]]==1)){
q.push(edge[cur][i]);
}
}
//calculate distances using BFS
for (int i=0;i<n;i++)
if (degree[i]!=0){
q.push(i);
dist[i]=0;
}
while (!q.empty()){
int cur=q.front();
q.pop();
for (int i=0;i<edge[cur].size();i++)
if (!live[edge[cur][i]]){
dist[edge[cur][i]]=dist[cur]+1;
live[edge[cur][i]]=true;
q.push(edge[cur][i]);
}
}
cout<<"Case #"<<nn<<":";
for (int i=0;i<n;i++)
cout<<" "<<dist[i];
cout<<endl;
}
}