CodeForces 131D Subway (dfs)

Question meaning: n points, n edges, undirected graph, find the distance from each point to the ring.

Solution: dfs
n edges, then there must be only one ring.

Consider whether dfs finds the ring and whether the vis record is accessed. If the point is accessed twice, the point must be on the ring, and path records the path.

If the output distance is also DFS, it is fine. I wanted to memorize it, but the result was written. It is enough to directly cut the dfs to the ring for each point, not t.

#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
const int MAXN = 10010;//点数
const int MAXM = 10010;//边数
struct Edge {
    
    
    int to, next;
}edge[MAXM];
int head[MAXN], tot;
void addedge(int u, int v) {
    
    
    edge[tot].to = v; edge[tot].next = head[u]; head[u] = tot++;
}

void init() {
    
    
    tot = 0;
    memset(head, -1, sizeof(head));
}
bool vis[MAXN];
int flag, path[MAXN];
void dfs(int x, int pre) {
    
    
    vis[x] = 1;
    for (int i = head[x]; ~i; i = edge[i].next) {
    
    
        int v = edge[i].to;
        if (v == pre) continue;
        path[v] = x;
        if (vis[v]) {
    
    
            flag = v;
            return;
        }
        dfs(v, x);
        if (flag) return;
    }
}
int d[MAXN];
int res;
void dfs2(int x, int l, int pre) {
    
    
    for (int i = head[x]; ~i; i = edge[i].next) {
    
    
        int v = edge[i].to;
        if (v == pre) continue;
        /*if (d[v]) {
            res = l + d[v];
            return;
        }*/
        if (vis[v]) {
    
    
            res = l;
            return;
        }
        dfs2(v, l + 1, x);
    }
}
int n, u, v, a[MAXN];
int main() {
    
    
    init();
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
    
    
        scanf("%d%d", &u, &v);
        addedge(u, v);
        addedge(v, u);
    }
    dfs(1, 0);
    memset(vis, 0, sizeof(vis));
    while (!vis[flag]) {
    
    
        vis[flag] = 1;
        flag = path[flag];
    }
    for (int i = 1; i <= n; i++) {
    
    
        if (vis[i]) printf("0 ");
        else {
    
    
            dfs2(i, 1, 0);
            printf("%d ", res);
        }
    }
    return 0;
}


Guess you like

Origin blog.csdn.net/qq_43680965/article/details/107721323