列表

详情


MT44. 图的遍历

描述

给定一张包含 个点、 N-1 条边的无向连通图,节点从 到 编号,每条边的长度均为 。假设你从 号节点出发并打算遍历所有节点,那么总路程至少是多少?

数据范围:

输入描述

第一行包含一个整数N。

接下来N-1行,每行包含两个整数X和Y,表示X号节点和Y号节点之间有一条边。

输出描述

输出总路程的最小值。

示例1

输入:

4
1 2
1 3
3 4

输出:

4

示例2

输入:

2
1 2

输出:

1

原站题解

C++ 解法, 执行用时: 24ms, 内存消耗: 7040KB, 提交时间: 2020-10-29

#include <bits/stdc++.h>
#define ll long long
#define met(a, b) memset(a, b, sizeof(a))
#define rep(i, a, b) for(int i = a; i <= b; i++)
#define bep(i, a, b) for(int i = a; i >= b; i--)
#define pb push_back
#define mp make_pair
#define debug cout << "KKK" << endl
#define ls num*2
#define rs num*2+1
#define re return 0
using namespace std;
const int mod = 1e9 + 7;
const double PI = acos(-1);
const ll INF = 4e18+1;
const int inf = 1e9 + 15;
const double eps = 1e-7;
const int maxn = 1e5 + 5;
struct node{
    int v, next;
}p[maxn*2];
int ne[maxn], tot, dep[maxn];
void add(int u, int v){
    p[++tot] = (node){v, ne[u]};
    ne[u] = tot;
}
bool vis[maxn];
void dfs(int now, int pre){
    vis[now] = 1;
    dep[now] = dep[pre] + 1;
    for(int i = ne[now]; i; i = p[i].next){
        int v = p[i].v;
        if(vis[v]) continue;
        dfs(v, now);
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    int n; cin >> n;
    rep(i, 2, n){
        int u, v; cin >> u >> v;
        add(u, v);
        add(v, u);
    }
    dfs(1, 0);
    ll tot = 0, ma = 0;
    rep(i, 1, n){
        tot += dep[i];
        ma = max((ll)dep[i], ma);
    }
    cout << (n-1)*2 - ma + 1 << endl;
    re;
}

C++ 解法, 执行用时: 24ms, 内存消耗: 7100KB, 提交时间: 2020-07-28

#include <bits/stdc++.h>
#define ll long long
#define met(a, b) memset(a, b, sizeof(a))
#define rep(i, a, b) for(int i = a; i <= b; i++)
#define bep(i, a, b) for(int i = a; i >= b; i--)
#define pb push_back
#define mp make_pair
#define debug cout << "KKK" << endl
#define ls num*2
#define rs num*2+1
#define re return 0
using namespace std;
const int mod = 1e9 + 7;
const double PI = acos(-1);
const ll INF = 4e18+1;
const int inf = 1e9 + 15;
const double eps = 1e-7;
const int maxn = 1e5 + 5;
struct node{
    int v, next;
}p[maxn*2];
int ne[maxn], tot, dep[maxn];
void add(int u, int v){
    p[++tot] = (node){v, ne[u]};
    ne[u] = tot;
}
bool vis[maxn];
void dfs(int now, int pre){
    vis[now] = 1;
    dep[now] = dep[pre] + 1;
    for(int i = ne[now]; i; i = p[i].next){
        int v = p[i].v;
        if(vis[v]) continue;
        dfs(v, now);
    }
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    int n; cin >> n;
    rep(i, 2, n){
        int u, v; cin >> u >> v;
        add(u, v);
        add(v, u);
    }
    dfs(1, 0);
    ll tot = 0, ma = 0;
    rep(i, 1, n){
        tot += dep[i];
        ma = max((ll)dep[i], ma);
    }
    cout << (n-1)*2 - ma + 1 << endl;
    re;
}

上一题