Codeforces Beta Round #95 (Div. 2) D. Subway 【简单dfs】
2013-03-30 12:35
399 查看
http://codeforces.com/problemset/problem/131/D
题目大意:由n个点组成的n条边构成一个环,求n个点与环的距离(环上的点数)。
进行两次dfs。第一次dfs找出环上所有的点并标记flag,第二次对所有flag的点进行深搜并标记。
题目大意:由n个点组成的n条边构成一个环,求n个点与环的距离(环上的点数)。
进行两次dfs。第一次dfs找出环上所有的点并标记flag,第二次对所有flag的点进行深搜并标记。
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <set> #include <map> #include <cmath> #include <queue> using namespace std; template <class T> void checkmin(T &t,T x) {if(x < t) t = x;} template <class T> void checkmax(T &t,T x) {if(x > t) t = x;} template <class T> void _checkmin(T &t,T x) {if(t==-1) t = x; if(x < t) t = x;} template <class T> void _checkmax(T &t,T x) {if(t==-1) t = x; if(x > t) t = x;} typedef pair <int,int> PII; typedef pair <double,double> PDD; typedef long long ll; #define foreach(it,v) for(__typeof((v).begin()) it = (v).begin(); it != (v).end ; it ++) const int N = 3030 , M = 6060; vector <int> g ; int flag ; bool vis ; int ok; void dfs1(int u,int f) { if(ok) return; vis[u] = 1; int sz = g[u].size(); for(int i=0;i<sz;i++) { int v = g[u][i]; if(v == f) continue; if(vis[v]) { flag[u] = 1; ok = v; return; } dfs1(v , u); if(ok) { if(ok == u) ok = -1 , flag[u] = 1; if(ok != -1) flag[u] = 1; return; } } return; } void debug(int n) { puts("debug"); for(int i=1;i<=n;i++) if(flag[i]) printf(" %d",i); puts("end of debug"); } int dep ; void dfs2(int u,int f,int d) { dep[u] = d; int sz = g[u].size(); for(int i=0;i<sz;i++) { int v = g[u][i]; if(v == f) continue; if(flag[v] || dep[v]) continue; dfs2(v , u , d + 1); } } int main() { int n; cin >> n; for(int i=0;i<n;i++) { int u , v ; cin >>u >> v; g[u].push_back(v); g[v].push_back(u); } dfs1(1 , -1); //debug(n); for(int i=1;i<=n;i++) { if(flag[i]) dfs2(i,-1,0); } cout << dep[1]; for(int i=2;i<=n;i++) cout << " " << dep[i]; cout << endl; return 0; }
相关文章推荐
- Educational Codeforces Round 34 div2 Hungry Student Problem 简单dfs
- Codeforces Beta Round #95 (Div. 2) -- D. Subway (DFS)
- Codeforces Round #267 (Div. 2)D(DFS+单词hash+简单DP)
- 【Codeforces Round 375 (Div 2) D】【简单dfs】Lakes in Berland
- Codeforces Round #267 (Div. 2)D(DFS+单词hash+简单DP)
- Codeforces Beta Round #95 (Div. 2) D. Subway dfs+bfs
- 用div+css实现简单下拉菜单效果
- div+css实现简单的弹出窗(背景变灰色)
- 超级简单的DIV布局
- 2016-12-10 dfs的简单总结
- Codeforces Round #277 (Div. 2) D. Valid Sets (DP DFS 思维)
- Codeforces Round #346 (Div. 2) E (dfs)
- bzoj 1088 简单dfs
- odeforces Beta Round #25 (Div. 2 Only), problem: (D) Roads not only in Berland 图论 DFS
- Codeforces Round #407 (Div. 2)-E-The Great Mixing-滚动数组或者dfs
- LeetCode Generate Parentheses 构造括号串(DFS简单题)
- Codeforces Round #428 (Div. 2) C. Journey(dfs deep
- Codeforces Round #369 (Div. 2) D. Directed Roads —— DFS找环 + 快速幂
- Codeforces Round #428 (Div. 2) C.Journey(dfs求期望)
- Codeforces Round #370 (Div. 2) C. Memory and De-Evolution【dfs+想法】