这题是要求N个点的一个拓扑序,且满足以下条件:编号1的位置尽可能靠前,在此基础上编号2的位置尽可能靠前……

  

  我看到这题的第一感觉:将拓扑排序用的队列改为优先队列,编号越小越早出来。

  但是连样例都过不了= =因为这样做是【字典序最小】,并不一定满足题目的条件(看样例就知道了,这样其实是早出队的元素编号尽量小,并不完全是编号小的早出队)

  那么怎么搞呢?正着不行还不让我们反着来吗>_>

 

  将所有边反向!搞逆拓扑序!这次我们让早出队的元素编号越大越好,也就是让编号越小的尽量靠后,因为在原序中靠前,就是在拓扑逆序中靠后。

  然后就AC辣~

 

  其实蒟蒻也不会证明……感性理解就是:对于编号小的元素,尽可能用编号比他大的进行拖延,让他晚出队,应该是有点贪心的思想吧= =

  证明:http://zyfzyf.is-programmer.com/posts/89618.html

      http://www.cnblogs.com/vb4896/p/4083650.html

P.S.这应该是这次胡策中最简单的一题了吧……反而放在C题的位置……

 1 /**************************************************************
 2     Problem: 4010
 3     User: Tunix
 4     Language: C++
 5     Result: Accepted
 6     Time:820 ms
 7     Memory:4520 kb
 8 ****************************************************************/
 9  
10 //Huce #7 C
11 #include<queue>
12 #include<vector>
13 #include<cstdio>
14 #include<cstdlib>
15 #include<cstring>
16 #include<iostream>
17 #include<algorithm>
18 #define rep(i,n) for(int i=0;i<n;++i)
19 #define F(i,j,n) for(int i=j;i<=n;++i)
20 #define D(i,j,n) for(int i=j;i>=n;--i)
21 using namespace std;
22  
23 int getint(){
24     int v=0,sign=1; char ch=getchar();
25     while(ch<'0'||ch>'9') {if (ch=='-') sign=-1; ch=getchar();}
26     while(ch>='0'&&ch<='9') {v=v*10+ch-'0'; ch=getchar();}
27     return v*sign;
28 }
29 typedef long long LL;
30 const int N=100010,INF=~0u>>2;
31 /*******************template********************/
32 int to[N<<1],next[N<<1],head[N],cnt;
33 void add(int x,int y){
34     to[++cnt]=y; next[cnt]=head[x]; head[x]=cnt;
35 }
36 int n,m,du[N];
37 void init(){
38     n=getint(); m=getint();
39     cnt=0; memset(head,0,sizeof head);
40     memset(du,0,sizeof du);
41     int x,y;
42     F(i,1,m){
43         x=getint(); y=getint();
44         swap(x,y);
45         add(x,y); du[y]++;
46     }
47 }
48 int ans[N],tot;
49 void solve(){
50     priority_queue<int>Q;
51     F(i,1,n) if (!du[i]) Q.push(i);
52     tot=0;
53     while(!Q.empty()){
54         int x=Q.top(); Q.pop();
55         ans[++tot]=x;
56         for(int i=head[x];i;i=next[i]){
57             du[to[i]]--;
58             if (du[to[i]]==0) Q.push(to[i]);
59         }
60     }
61     if (tot==n) {D(i,tot,1) printf("%d ",ans[i]); puts("");} 
62     else puts("Impossible!");
63 }
64      
65 int main(){
66 #ifndef ONLINE_JUDGE
67     freopen("C.in","r",stdin);
68 //  freopen("output.txt","w",stdout);
69 #endif
70     int T=getint();
71     while(T--){
72         init();
73         solve();
74     }
75     return 0;
76 }
View Code

相关文章: