zoukankan      html  css  js  c++  java
  • noip模拟赛(10.4) 字典序(dictionary)

    【题目描述】

    你需要构造一个1~n的排列,使得它满足m个条件,每个条件形如(ai,bi),表示ai必须在bi前面。在此基础上,你需要使它的字典序最小。

    【输入数据】

    第一行两个正整数n,m。接下来m行每行两个数ai,bi。

    【输出数据】

          输出一行n个整数表示答案。如果不存在这样的排列,输出-1。

    【样例读入】

    5 4

    5 4

    5 3

    4 2

    3 2

    【样例输出】

    1 5 3 4 2

    【数据范围】

    对于20%的数据,n,m<=10。

    对于40%的数据,n,m<=200。

    对于60%的数据,n,m<=1000。

    对于100%的数据,n,m<=100000。

    【题解】

    按字典序的题目可以想到建图。要保证题目要求的先后顺序则在点ai和bi间建一条指向bi的有向边,并将无入度的点插入一个大根堆。每次弹出堆顶的元素,按弹出的先后顺序在ans数组中,并且更新该点的出度,将该点的出边全部删除,若删除产生了其他无入度点,则将其也插入堆中,如此往复。

    #include<queue>
    #include<vector>
    #include<cstdio>
    #include<cstdlib>
    #include<algorithm>
    using namespace std;
    const int N=101111;
    inline int read()
    {
    	int x=0,c=getchar(),f=1;
    	while(c<48||c>57){if(c=='-')f=-1;c=getchar();}
    	while(c>47&&c<58)x=x*10+c-48,c=getchar();
    	return x*f;
    }
    struct edge{
    	int v,nxt;
    }e[N];
    int n,m,ect,sum,fst[N],ind[N],ans[N];
    priority_queue<int,vector<int>,greater<int> > q;
    int main()
    {
    	n=read(),m=read();
    	while(m--){
    		int u=read(),v=read();
    		e[++ect].nxt=fst[u];
    		fst[u]=ect;
    		e[ect].v=v;
    		ind[v]++;
    	}
    	for(int i=1;i<=n;i++)
    		if(!ind[i]){
    			q.push(i);
    			sum++;
    		}
    	while(!q.empty()){
    		int x=q.top();
    		q.pop();
    		ans[++ans[0]]=x;
    		for(int i=fst[x];i;i=e[i].nxt){
    			ind[e[i].v]--;
    			if(!ind[e[i].v]){
    				q.push(e[i].v);
    				sum++;
    			}
    		}
    	}
    	if(sum<n)
    		puts("-1");
    	else
    		for(int i=1;i<=n;i++)
    			printf("%d ",ans[i]);
    	return 0;
    }



  • 相关阅读:
    Unity The Method Signature Matching Rule
    Unity The Property Matching Rule
    Unity The Type Matching Rule
    Unity The Custom Attribute Matching Rule
    Unity The Member Name Matching Rule
    Unity No Policies
    Unity The Return Type Matching Rule
    Unity The Parameter Type Matching Rule
    Unity The Namespace Matching Rule
    关于TSQL递归查询的(转)
  • 原文地址:https://www.cnblogs.com/keshuqi/p/5957689.html
Copyright © 2011-2022 走看看