Luo Gu P3243 [[HNOI2015] food production]

At first glance this question, suddenly ignorant force, a \ (SB \) topology title sequence turned out to be black, spray the spot laugh.

\ (Of \) \ (Course, \) , which is a problem I do heap. (In fact, is a priority queue, so handwriting heapRubbishHow could I use it)

\ ((1) \) First built in Fig. If \ (X \) requires \ (Y \) in front of it from \ (Y \) to \ (X \) connected edges.

\ ((2) \) then no edge point of the first reactor was added. Takes out the minimum number down from the stack.

\ ((3) \) and then connect it to the point all the heap. Until heap space. If the point is not taken \ (n-\) th outputs possible. Otherwise, output down point just fine.

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
const int MAX_N=100010;
struct EDGE{
    int v,nxt;
}e[MAX_N];
int d,n,m,in[MAX_N],cnt,head[MAX_N],a[MAX_N];
priority_queue<int> q;
inline int read(){
    int x=0,f=1;
    char c=getchar();
    while(c<'0'||c>'9'){
        if(c=='-'){
            f=-1;
        }
        c=getchar();
    }
    while(c>='0'&&c<='9'){
        x=(x<<1)+(x<<3)+c-'0';
        c=getchar();
    }
    return x*f;
}
void add(int u,int v){
    e[++cnt].v=v;
    e[cnt].nxt=head[u];
    head[u]=cnt;
}
bool bfs(){
    while(!q.empty()){
        int p=q.top();
        q.pop();
        cnt++;
        a[cnt]=p;
        for(int i=head[p];i;i=e[i].nxt){
            int v=e[i].v;
            in[v]--;
            if(!in[v]){
                q.push(v);
            }
        }
    }
    return cnt==n;
}
int main(){
    d=read();
    while(d--){
        memset(in,0,sizeof(in));
        memset(head,0,sizeof(head));
        cnt=0;
        n=read(),m=read();
        for(int i=1;i<=m;i++){
            int x,y;
            x=read(),y=read();
            add(y,x);
            in[x]++;
        }
        for(int i=1;i<=n;i++){
            if(!in[i]){
                q.push(i);
            }
        }
        cnt=0;
        if(bfs()){
            for(int i=n;i>=1;i--){
                printf("%d ",a[i]);
            }
            printf("\n");
        }else{
            printf("Impossible!\n");
        }
    }
    return 0;
}
/*
3 
5 4 
5 4 
5 3 
4 2 
3 2 
3 3 
1 2 
2 3 
3 1 
5 2 
5 2 
4 3 

1 5 3 4 2 
Impossible! 
1 5 2 4 3 
*/

Guess you like

Origin www.cnblogs.com/errichto/p/11317983.html