题目描述
题目:https://vjudge.net/problem/HDU-1285#author=YaoBIG
有翻译就不说了,但是这道题可能有个地方想不懂:
样例里,4和1、2哪个高?其实理解起来就是:1打过了2,那么1就比2高,但是不确定4能不能打得过2,而4又打过了3,那么,4应该和2同一级,比1低1级。
思路分析
按照上面的理解,这道题也很明显肯得出来就是拓扑排序:先遍历入度小的点,在遍历入度大的点。根据这道题需要输出编号小的(字典序小的),所以需要使用优先队列+bfs。顺便可以熟悉下优先队列的用法。
完整代码
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
const int maxn=600;
int enter_val[maxn]={0};
bool vis[maxn]={0};
int n,m;
vector<int> edge[maxn];
void bfs()
{
priority_queue<int,vector<int>,greater<int>> que;
for(int i=1;i<=n;i++)
{
if(enter_val[i]==0)
{
que.push(i);
vis[i]=1;
}
}
while(!que.empty())
{
int a=que.top();
que.pop();
cout<<a;
for(int i=0;i<edge[a].size();i++)
{
enter_val[edge[a][i]]--;
if(enter_val[edge[a][i]]==0)
{
vis[edge[a][i]]=1;
que.push(edge[a][i]);
}
}
if(!que.empty()) cout<<" ";
else cout<<endl;
}
}
int main()
{
while(cin>>n>>m)
{
for(int i=0;i<maxn;i++) edge[i].clear();
memset(enter_val,0,sizeof(enter_val));
while(m--)
{
int a,b;
cin>>a>>b;
edge[a].push_back(b);
enter_val[b]++;
}
bfs();
}
return 0;
}