NYOJ 496 拓扑排序

解决拓扑排序分;

找到入度为0的点----->>删除与此点有关的边----->>>输出该点---------->> 重复操作----->>>>判断点的个数 = ? 总点数   yes : no

#include <stdio.h>
#include<string.h>
#include <queue>
using namespace std;
int m,n;
int into[100];  
int map[27][27];
void topusort()
{
    queue <int> Q;
    queue <char> S;
    while(!S.empty()) S.pop();
    int count = 0,cn=0,flog = 0;
    for(int i=1;i<=m;i++)
    {

    if(!into[i])      //  首先寻找一个入度为0的点
    {
        Q.push(i);
        cn++;
    }
    }
 if(cn>1) flog = 1;

    while(!Q.empty())
     {
         cn = 0;
            int k = Q.front();
            Q.pop();
            count++;
            S.push(k+'A'-1);
            for(int i=1;i<=m;i++)
            {
                if(map[k][i])
                {
                    into[i]--;      //此处为去边
                    if(!into[i])
                    {
                        cn++;
                        Q.push(i);
                    }

                }

        if(cn>1) flog = 1 ;
            }

    }
      if(count<m||flog)
      printf("No Answer\n");
      else
      {
          while(!S.empty())
          {
              printf("%c",S.front());
              S.pop();
          }
          printf("\n");
      }
}
int main()
{

    int N;
    char A,B;
    scanf("%d",&N);
    while(N--)
    {
        memset(into,0,sizeof(into));
        memset(map,0,sizeof(map));
        scanf("%d%d",&m,&n);
        getchar();
        for(int i=1;i<=n;i++)
        {
              scanf("%c %c",&A,&B);getchar();
              int a = A-'A'+1;
              int b = B-'A'+1;
               map[a][b] = 1;    // 转化成图
              into[b]++;   //统计入度
         }
   topusort();

    }
}



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值