CodeForce 117C Cycle DFS
Posted cautx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了CodeForce 117C Cycle DFS相关的知识,希望对你有一定的参考价值。
A tournament is a directed graph without self-loops in which every pair of vertexes is connected by exactly one directed edge. That is, for any two vertexes u and v (u ≠ v) exists either an edge going from u to v, or an edge from v to u.
You are given a tournament consisting of n vertexes. Your task is to find there a cycle of length three.
Input
The first line contains an integer n (1 ≤ n ≤ 5000). Next n lines contain the adjacency matrix A of the graph (without spaces). Ai, j = 1 if the graph has an edge going from vertex i to vertex j, otherwise Ai, j = 0. Ai, j stands for the j-th character in the i-th line.
It is guaranteed that the given graph is a tournament, that is, Ai, i = 0, Ai, j ≠ Aj, i (1 ≤ i, j ≤ n, i ≠ j).
OutputPrint three distinct vertexes of the graph a1, a2, a3 (1 ≤ ai ≤ n), such that Aa1, a2 = Aa2, a3 = Aa3, a1 = 1, or "-1", if a cycle whose length equals three does not exist.
If there are several solutions, print any of them.
Examples5
00100
10000
01001
11101
11000
1 3 2
5
01111
00000
01000
01100
01110
-1
OJ-ID:
CodeForce 117C
author:
Caution_X
date of submission:
20190930
tags:
DFS
description modelling:
给定一个有向图,边权都为1,问能否找到权值和为3的环,找到则输出对应的点标号,否则输出-1
major steps to solve it:
1.vis[]表示该点是否访问过
2.从一个未被访问过的点开始DFS,找到与该点相连且未被访问过的点继续DFS
3.如果形成了环,结束DFS,否则继续2操作
AC CODE:
#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <fstream> #include <algorithm> #include <cmath> #include <queue> #include <stack> #include <vector> #include <map> #include <set> #include <iomanip> using namespace std; //#pragma comment(linker, "/STACK:102400000,102400000") #define maxn 5005 #define MOD 1000000007 #define mem(a , b) memset(a , b , sizeof(a)) #define LL long long #define ULL unsigned long long #define FOR(i , n) for(int i = 1 ; i<= n ; i ++) typedef pair<int , int> pii; const long long INF= 0x3fffffff; int n , flag; int a , b , c; char arr[maxn][maxn]; int vis[maxn]; void dfs(int u , int v) { if(a && b && c) return; vis[u] = 1; for(int i = 0 ; i < n &&(!a ||!b || !c); i ++) { if(arr[u][i] == ‘1‘ ) { if(v != -1 && arr[i][v] == ‘1‘) { a = v + 1 , b = u + 1 , c = i + 1; return ; } if(!vis[i]) dfs(i , u); } } } int main() { while(scanf("%d" , &n) != EOF) { mem(vis , 0); for(int i = 0 ; i < n; i ++) { scanf("%s" , arr[i]); } flag = 0; a = b = c = 0; for(int i = 0 ; i < n ; i ++) { if(!vis[i]) { dfs(i , -1); } } if(!a) printf("-1 "); else printf("%d %d %d " , a , b , c); } return 0; }
以上是关于CodeForce 117C Cycle DFS的主要内容,如果未能解决你的问题,请参考以下文章
CodeForce 377 A mazes(dfs+连通性问题)
CodeForce-812B Sagheer, the Hausmeister(DFS)
codeforce Edu49 - 1027D. Mouse Hunt DFS 环
codeforce -39E-What Has Dirichlet Got to Do with That?(博弈+dfs)