拓扑排序,但题目保证了不会形成环,故可实现全部输出;而由于答案唯一性,需要输出字典序最小的。我的策略是建立一个同步的跟踪各个节点入度数的数组,随着排序的进行不断更新,然后添加新的入度为0的节点到一个set里面,每次输出最前的,也就是最小的那个节点,以此来保证字典序最小。
Run Time: 0.44sec
Run Memory: 6216KB
Code length: 969Bytes
SubmitTime: 2011-12-22 17:29:39
// Problem#: 1940
// Submission#: 1111245
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <cstdio>
#include <set>
#include <vector>
using namespace std;
int main()
{
int T;
int n, m;
int i, j;
set<int> s;
int indegree[ 100001 ] = { };
vector<int> v[ 100001 ];
scanf( "%d", &T );
while ( T-- ) {
scanf( "%d%d", &n, &m );
while ( m-- ) {
scanf( "%d%d", &i, &j );
v[ i ].push_back( j );
indegree[ j ]++;
}
for ( i = 1; i <= n; i++ ) {
if ( indegree[ i ] == 0 )
s.insert( i );
}
while ( !s.empty() ) {
i = *s.begin();
printf( "%d ", i );
s.erase( s.begin() );
while ( !v[ i ].empty() ) {
if ( --indegree[ v[ i ].back() ] == 0 )
s.insert( v[ i ].back() );
v[ i ].pop_back();
}
}
printf( "\n" );
}
return 0;
}