CF1385E Directing Edges 拓扑序
作者:互联网
文章目录
题意:
给你一个图和若干个边,有些是有向边,有些是无向边,让你给无向边定向,使得最终的图是 D A G DAG DAG。
思路:
题目让构造
D
A
G
DAG
DAG,比较容易想到拓扑序。
首先我们需要知道拓扑图中的点都是从拓扑序小的指向拓扑序大的,所以我们就可以根据这个连边。
在原来有向图上做一遍拓扑排序,有环的话直接无解就好啦,否则我们就按照拓扑序小的向拓扑序大的连边,这样一定可以保证是正确的。
// Problem: E. Directing Edges
// Contest: Codeforces - Codeforces Round #656 (Div. 3)
// URL: https://codeforces.com/contest/1385/problem/E
// Memory Limit: 256 MB
// Time Limit: 3000 ms
//
// Powered by CP Editor (https://cpeditor.org)
//#pragma GCC optimize("Ofast,no-stack-protector,unroll-loops,fast-math")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4.1,sse4.2,avx,avx2,popcnt,tune=native")
//#pragma GCC optimize(2)
#include<cstdio>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>
#include<cctype>
#include<vector>
#include<set>
#include<queue>
#include<algorithm>
#include<sstream>
#include<ctime>
#include<cstdlib>
#define X first
#define Y second
#define L (u<<1)
#define R (u<<1|1)
#define pb push_back
#define mk make_pair
#define Mid (tr[u].l+tr[u].r>>1)
#define Len(u) (tr[u].r-tr[u].l+1)
#define random(a,b) ((a)+rand()%((b)-(a)+1))
#define db puts("---")
using namespace std;
//void rd_cre() { freopen("d://dp//data.txt","w",stdout); srand(time(NULL)); }
//void rd_ac() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//AC.txt","w",stdout); }
//void rd_wa() { freopen("d://dp//data.txt","r",stdin); freopen("d://dp//WA.txt","w",stdout); }
typedef long long LL;
typedef unsigned long long ULL;
typedef pair<int,int> PII;
const int N=1000010,mod=1e9+7,INF=0x3f3f3f3f;
const double eps=1e-6;
int n,m;
int d[N],dag[N];
vector<int>v[N];
struct Edge {
int a,b,op;
}edge[N];
bool check() {
int id=0;
queue<int>q;
for(int i=1;i<=n;i++) if(!d[i]) q.push(i);
while(q.size()) {
int u=q.front(); q.pop();
dag[u]=++id;
for(auto x:v[u]) {
if(--d[x]==0) q.push(x);
}
}
if(id!=n) return false;
puts("YES");
for(int i=1;i<=m;i++) {
if(edge[i].op) {
printf("%d %d\n",edge[i].a,edge[i].b);
continue;
}
if(dag[edge[i].a]<dag[edge[i].b]) printf("%d %d\n",edge[i].a,edge[i].b);
else printf("%d %d\n",edge[i].b,edge[i].a);
}
return true;
}
int main()
{
// ios::sync_with_stdio(false);
// cin.tie(0);
int _; cin>>_;
while(_--) {
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) d[i]=0,v[i].clear();
for(int i=1;i<=m;i++) {
scanf("%d%d%d",&edge[i].op,&edge[i].a,&edge[i].b);
if(edge[i].op) v[edge[i].a].pb(edge[i].b),d[edge[i].b]++;
}
if(!check()) puts("NO");
}
return 0;
}
/*
*/
标签:int,拓扑,Directing,edge,Edges,CF1385E,freopen,include,define 来源: https://blog.csdn.net/m0_51068403/article/details/117351629