</pre>题目链接:<a target=_blank target="_blank" href="http://acm.hdu.edu.cn/showproblem.php?pid=1285">http://acm.hdu.edu.cn/showproblem.php?pid=1285</a><p></p><p><table cellspacing="0" cellpadding="0" width="980" align="center" border="0" style="word-wrap:break-word"><tbody><tr><td><div id="rollword" align="center"><marquee width="600"><span style="margin-right:20px"><a target=_blank target="_blank" href="http://acm.hdu.edu.cn/discuss/public/post/reply.php?postid=20191&messageid=1&deep=0" style="color:red">NEW~ 关于举办计算机学院大学生程序设计竞赛(2014'11)的报名通知</a></span></marquee></div></td></tr><tr><td align="center"><h1 style="color:#1a5cc8">确定比赛名次</h1><span size="+0" style=""><strong><span style="font-size:12px; font-family:Arial; color:green">Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 12975 Accepted Submission(s): 5209</span></strong></span><div class="panel_title" align="left">Problem Description</div><div class="panel_content">有N个比赛队(1<=N<=500),编号依次为1,2,3,。。。。,N进行比赛,比赛结束后,裁判委员会要将所有参赛队伍从前往后依次排名,但现在裁判委员会不能直接获得每个队的比赛成绩,只知道每场比赛的结果,即P1赢P2,用P1,P2表示,排名时P1在P2之前。现在请你编程序确定排名。</div><div class="panel_bottom"> </div><div class="panel_title" align="left">Input</div><div class="panel_content">输入有若干组,每组中的第一行为二个数N(1<=N<=500),M;其中N表示队伍的个数,M表示接着有M行的输入数据。接下来的M行数据中,每行也有两个整数P1,P2表示即P1队赢了P2队。</div><div class="panel_bottom"> </div><div class="panel_title" align="left">Output</div><div class="panel_content">给出一个符合要求的排名。输出时队伍号之间有空格,最后一名后面没有空格。其他说明:符合条件的排名可能不是唯一的,此时要求输出时编号小的队伍在前;输入数据保证是正确的,即输入数据确保一定能有一个符合要求的排名。</div><div class="panel_bottom"> </div><div class="panel_title" align="left">Sample Input</div><div class="panel_content"><pre><div style="font-family:Courier New,Courier,monospace">4 3
1 2
2 3
4 3</div>
Sample Output
1 2 4 3
Author
SmallBeer(CML)
Source
拓扑排序模板题。
题目要求以从小到大的顺序输出,自然可以想到用一个优先队列来维护,当然你想求出所有的拓扑排序序列(算法思想一致,再加个深搜就可以了),然后对它们进行排序取最小的就OK啦。
不多说了,模板题就直接上模板了。
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<iostream>
#include<algorithm>
#include<sstream>
#include<vector>
#include<map>
#include<list>
#include<set>
#include<queue>
using namespace std;
const int maxn=1005,maxe=100005,inf=1<<29;
struct node
{
int to,next,w;
}edge[maxe];
int head[maxn],n,m,cnt,in[maxn],id[maxn],iq;
void add(int from,int to)
{
edge[cnt].to=to;
edge[cnt].next=head[from];
head[from]=cnt++;
}
void topology()
{
priority_queue<int,vector<int>,greater<int> >q;
for(int i=1;i<=n;i++)
if(!in[i]) q.push(i);
iq=0;
while(!q.empty())
{
int t=q.top();q.pop();
id[iq++]=t;
//printf("%d\n",t);
for(int j=head[t];j!=-1;j=edge[j].next)
{
in[edge[j].to]--;
if(in[edge[j].to]==0) q.push(edge[j].to);
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
memset(head,-1,sizeof(head));
memset(in,0,sizeof(in));
cnt=0;
for(int i=1;i<=m;i++)
{
int from,to;
scanf("%d%d",&from,&to);
in[to]++;
add(from,to);
}
topology();
for(int i=0;i<iq-1;i++) printf("%d ",id[i]);
printf("%d\n",id[iq-1]);
}
return 0;
}