codeforces 1385E 拓扑排序

该博客介绍了如何利用拓扑排序解决codeforces上的1385E题目。题目要求在保持图无环的前提下,为未定向边决定方向。博主分析了先判断已定向边是否存在环,若无环则可通过拓扑排序确定未定向边的方向,以保证图的有向无环性质。文章提供了基于拓扑排序的解决方案。

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

1385E 2000的题
题意:给你一个图,n个点,m条边,但这m条边有些是定向的,有些是未定向的,需要你去决定方向,问你是否能让这个图不形成环,而且要对所有未定向的边定向。
思路:拓扑排序可以判断一个图是否是有向无环的,所以可以用到,先对以定向的边进行判断是否已经形成了环,如果形成了环那就肯定不能符合条件,反之,如果未形成环,那么就一定能符合条件,按照拓扑排序出来的顺序,可以用一个数组pos记录,当pos【x】<pos【y】时,即意味着x在y之前就出来了,所以可以加上x->y的一条边是对这个图的是否有环是没有影响的。代码就出来了

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <cmath>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <unordered_map>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> pii;
#define rep(i, a, n) for(int i = a; i <= n; i++)
#define per(i, a, n) for(int i = n; i >= a; i--)
#define IOS std::ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
#define fopen freopen("file.in","r",stdin);freopen("file.out","w",stdout);
#define fclose fclose(stdin);fclose(stdout);
#define PI 3.14159265358979323846
const int inf = 1e9;
const ll onf = 1e18;
const int maxn = 2e5+10;
inline int read(){
    int x=0,f=1;char ch=getchar();
    while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
    while (ch>='0'&&ch<='9'){x=(x<<3)+(x<<1)+(ch^48);ch=getchar();}
    return x*f;
}
std::vector<int> g[maxn];
inline void cf(){
    int t = read();
    while(t--){
        int n=read(), m=read();
        std::vector<pii> edges;
        std::vector<int> in(n+1);
        std::vector<int> pos(n+1);
        for(int i = 1; i <= n; i++){
            g[i].clear();pos[i]=in[i]=0;
        }
        edges.clear();
        for(int i = 0; i < m; i++){
            int x=read(), u=read(), v=read();
            if(x==1){
                g[u].push_back(v);
                in[v]++;
            }
            edges.push_back({u,v});
        }
        // 典型的拓扑排序
        queue<int> q;
        int cnt = 0;
        for(int i = 1; i <= n; i++){
            if(in[i]==0) q.push(i);
        }
        while(!q.empty()){
            int u = q.front();
            q.pop();
            pos[u] = ++cnt; //记录拓扑的顺序
            for(auto to : g[u]){
                in[to]--;
                if(in[to]==0) q.push(to);
            }
        }
        if(cnt==n){
            printf("YES\n");
            for(auto [x,y] : edges){
                if(pos[x] <= pos[y]) printf("%d %d\n", x, y);
                else printf("%d %d\n", y, x);
            }
        }else printf("NO\n");
    }
    return ;
}
signed main(){
    cf();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值