
Untitled
By: a guest on
Aug 5th, 2012 | syntax:
None | size: 2.58 KB | hits: 11 | expires: Never
#include <cstdio>
#include <iostream>
using std::cin;
using std::cout;
class Graph {
public:
int N;
virtual ~Graph() = 0 {}
virtual void addEdge(int i, int j) = 0;
virtual bool dfs (int v, int colour[], int cycleSt, int cycleEnd, int p[]) = 0;
};
struct list{
int value;
list* next;
};
class List: public Graph {
list **l;
public:
List(){
this->l=NULL;
}
List(int n){
N = n;
this->l=new list*[n+1];
for(int i=1; i<=N; i++){
this->l[i] = new list;
this->l[i]->next = NULL;
this->l[i]->value = i;
}
}
void addEdge(int i, int j);
bool dfs (int v, int colour[], int cycleSt, int cycleEnd, int p[]);
void printList();
~List(){
delete l;
}
};
void List::addEdge(int i, int j) {
if(this->l[i]->next == NULL){
this->l[i]->next = new list;
this->l[i]->next->next = NULL;
this->l[i]->next->value = j;
} else {
list *temp;
temp = l[i]->next;
while(temp->next !=NULL) {
temp = temp->next;
}
temp->next = new list;
temp->next->next = NULL;
temp->next->value = j;
}
}
/*
void List::printList () {
for ( int i = 1; i <= N; i++ ) {
std::cout << i << " ";
list* temp = l[i];
if ( temp != NULL ) {
temp = temp->next;
}
while ( temp != NULL ) {
std::cout << temp->value << " ";
temp = temp->next;
}
printf ("\n");
}
}
*/
bool List::dfs (int v, int colour[],int cycleSt,int cycleEnd,int p[]) {
colour[v] = 1;
while (l[v] != NULL){
int t = l[v]->value;
if (colour[t] == 0) {
p[t] = v;
if (dfs(t, colour, cycleSt, cycleEnd, p))
return true;
}
else
if (colour[t] == 1) {
cycleSt = v;
cycleEnd = t;
return true;
}
l[v] = l[v]->next;
}
colour[v] = 10;
return false;
}
int main() {
int n, m;
int cycleSt = -1;
int cycleEnd = 0;
int colour[500000] = {0};
int p[500000];
freopen ("cycle.in", "r", stdin);
freopen ("cycle.out", "w", stdout);
scanf("%d %d\n", &n, &m);
List g(m);
int a, b;
for (int i = 1; i <= m; i++) {
scanf("%d %d\n", &a, &b);
g.addEdge(a, b);
}
for (int i = 1; i <= n; ++i)
if (colour[i] == 0)
if (g.dfs(i, colour, cycleSt, cycleEnd, p))
break;
if (cycleSt == -1)
printf("NO");
else
{
printf("YES\n");
int order[500000];
int i = 0;
for (int v = cycleSt; v != cycleSt; v = p[v])
{
order[i] = v;
++i;
}
order[i] = cycleSt;
for (i; i >= 0; i--)
printf("%d ", order[i]);
}
//g.printList();
return 0;
}