Luo Gu P3243 [HNOI2015] dishes made solution to a problem

Daily questions day60 punch

Analysis

This question is one can feel a topological sorting, but there will be problems because of the smallest sort lexicographical order (see third sample) is the main reason for each choice has aftereffect, whereas from the back does not exist this problem because each sub-task is a point.

So that is sort of a bare topology.

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define int long long
#define maxn 100000+10
#define rep(i,s,e) for(register int i=s;i<=e;++i)
#define dwn(i,s,e) for(register int i=s;i>=e;--i)
using namespace std;
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*10+c-'0'; c=getchar();}
    return f*x;
}
inline void write(int x)
{
    if(x<0) {putchar('-'); x=-x;}
    if(x>9) write(x/10);
    putchar(x%10+'0');
}
int T;
int n,m,cnt,num;
int head[maxn],ans[maxn];
int degree[maxn],book[maxn];
struct node
{
    int v,nex;
}edge[maxn];
priority_queue<int> q;
inline void add(int x,int y)
{
    edge[++cnt].v=y;
    edge[cnt].nex=head[x];
    head[x]=cnt;
}
signed main()
{
    T=read();
    while(T--)
    {
        cnt=0;
        num=0;
        memset(head,0,sizeof(head));
        memset(degree,0,sizeof(degree));
        n=read();m=read();
        rep(i,1,m)
        {
            int x=read(),y=read();
            add(y,x);
            degree[x]++;
        }
        rep(i,1,n) 
            if(degree[i]==0) q.push(i);
        while(!q.empty())
        {
            int top=q.top();
            q.pop();
            ans[++num]=top;
            for(int i=head[top];i;i=edge[i].nex)
            {
                int to=edge[i].v;
                --degree[to];
                if(degree[to]==0) q.push(to);
            }
        }
        if(num<n) {printf("Impossible!\n"); continue;}
        dwn(i,n,1) {write(ans[i]); putchar(' ');}
        printf("\n");
    }
    return 0;
}

Please Gangster treatise(Anyway, I do not know what that means treatise)

Guess you like

Origin www.cnblogs.com/handsome-zyc/p/12039927.html