NC24868. [USACO 2009 Dec G]Dizzy Cows
描述
Consider this example: 1-->2 | /| | / | |/ | 3<--4 The cow paths between pastures 1 and 3, 2 and 3, and 2 and 4 are two-way paths. One-way paths connect 1 to 2 and also 4 to 3. One valid way to convert the two-way paths into one-way paths in such a way that there are no cycles would be to direct them from 1 to 3, from 2 to 3, and from 3 to 4: 1-->2 | /| | / | vL v 3<--4
输入描述
* Line 1: Three space separated integers: N, M1, and M2
* Lines 2..1+M1: Line i+1 describes a one-way cow path using two space separated integers: Ai and Bi
* Lines 2+M1..1+M1+M2: Line i+M1+1 describes a two-way cow path using two space separated integers: Xi and Yi
输出描述
* Lines 1..M2: Line i should contain two space-separated integers: either Xi and Yi or Yi and Xi, depending on the direction assigned to the i-th two-way path. The two-way paths must appear in the same order in the output as they do in the input. If there is no solution, output "-1" on a single line.
示例1
输入:
4 2 3 1 2 4 3 1 3 4 2 3 2
输出:
1 3 4 2 2 3
C++14(g++5.4) 解法, 执行用时: 2ms, 内存消耗: 372K, 提交时间: 2019-08-20 11:27:35
#include<stdio.h> #define fo(i,a,b) for(int i=a;i<=b;i++) #define fd(i,a,b) for(int i=a;i>=b;i--) int n,m,M,xx,yy,du[110000],be[110000],et,q[110000],he,ta,r[110000]; struct edg{ int y,ne; }e[220000]; inline void add_edge(int x,int y){ e[++et].y=y; e[et].ne=be[x]; be[x]=et; du[y]++; } int main(){ scanf("%d%d%d",&n,&m,&M); while (m--){ scanf("%d%d",&xx,&yy); add_edge(xx,yy); } fo(i,1,n) if (!du[i]){ q[++ta]=i; r[i]=ta; } he=1; while (he<=ta){ for(int i=be[q[he]];i;i=e[i].ne){ du[e[i].y]--; if (!du[e[i].y]){ q[++ta]=e[i].y; r[e[i].y]=ta; } } he++; } if (ta<n){ printf("-1\n"); return 0; } while (M--){ scanf("%d%d",&xx,&yy); if (r[xx]<r[yy]) printf("%d %d\n",xx,yy);else printf("%d %d\n",yy,xx); } return 0; }
C++(clang++ 11.0.1) 解法, 执行用时: 5ms, 内存消耗: 2696K, 提交时间: 2022-09-12 21:44:59
#include<bits/stdc++.h> using namespace std; vector<int> a[100010]; int pos[100010]; bool v[100010]; int n,p1,p2,cnt,x,y; void dfs(int x){ for(int i=0;i<a[x].size();i++){ if(!v[a[x][i]]){ dfs(a[x][i]); } } pos[x]=cnt++; v[x]=1; } int main(){ scanf("%d%d%d",&n,&p1,&p2); for(int i=0;i<p1;i++){ scanf("%d%d",&x,&y); a[x].push_back(y); } for(int i=1;i<=n;i++){ if(!v[i]){ dfs(i); } } for(int i=0;i<p2;i++){ scanf("%d%d",&x,&y); if(pos[x]>pos[y]){ printf("%d %d\n",x,y); }else{ printf("%d %d\n",y,x); } } return 0; }