Topological Sorting URAL - 1280

本文介绍了一种验证编程学习计划正确性的方法。针对特定的学科限制条件,利用拓扑排序来判断给定的学习顺序是否合理。适用于编程竞赛训练场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Michael wants to win the world championship in programming and decided to study N subjects (for convenience we will number these subjects from 1 to N). Michael has worked out a study plan for this purpose. But it turned out that certain subjects may be studied only after others. So, Michael’s coach analyzed all subjects and prepared a list of M limitations in the form “ si ui” (1 ≤ si, uiN; i = 1, 2, …, M) , which means that subject si must be studied before subject ui.
Your task is to verify if the order of subjects being studied is correct.
Remark. It may appear that it’s impossible to find the correct order of subjects within the given limitations. In this case any subject order worked out by Michael is incorrect.
Limitations
1 ≤ N ≤ 1000; 0 ≤ M ≤ 100000.
Input
The first line contains two integers N and M ( N is the number of the subjects, M is the number of the limitations). The next M lines contain pairs si, ui, which describe the order of subjects: subject si must be studied before ui. Further there is a sequence of N unique numbers ranging from 1 to N — the proposed study plan.
Output
Output a single word “YES” or “NO”. “YES” means that the proposed order is correct and has no contradictions with the given limitations. “NO” means that the order is incorrect.
Example
inputoutput
5 6
1 3
1 4
3 5
5 2
4 2
1 2
1 3 4 5 2
YES
5 6
1 3
1 4
3 5
5 2
4 2
1 2
1 2 4 5 3
NO


题意

给你一些两个数之间的先后顺序,问某个顺序是否成立

思路

拓扑排序

#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[20];
ll flag;
ll w;
void f(ll x)
{
    ll i;
    if(x==1)
    {
        flag=1;
        return ;
    }
    for(i=9;i>=2;i--)
    {
        if(x%i==0)
        {
            a[i]++;
            f(x/i);
            return ;
        }
    }
}
int main()
{
    ll n,i;
    flag=0;
    cin>>n;
    w=0;
    if(n==0)
    {
        printf("10\n");
        return 0;
    }
    if(n==1)
    {
        printf("1\n");
        return 0;
    }
    memset(a,0,sizeof(a));
    f(n);
//    for(i=2;i<=9;i++)
//        printf("%d ",a[i]);
    if(!flag) printf("-1\n");
    else
    {
        for(i=2;i<=9;i++)
        {
            while(a[i])
            {
                printf("%lld",i);
                a[i]--;
            }
        }
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值