F题

#include <iostream>
#include <bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <set>
#include <queue>
#include <map>
#include <deque>
#include <cstdlib>
#define lowbit(x) ((x) & -(x))
#define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
const int maxn = 1e6 + 7;
const int INF = 0x3f3f3f3f;
typedef long long ll;
using namespace std;
const ll mod = 1e9 + 7;
const double pi = acos(-1.0);
inline int read(){
    int x = 0, f = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9'){
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9'){
        x = (x<<1) + (x<<3) + (ch^48);
        ch = getchar();
    }
    return x * f;
}
vector<int>v[maxn];
int ans;
int fa[maxn];
int find(int x){
    return fa[x] == x ? x : fa[x] = find(fa[x]);
}
void union_set(int x,int y){
    fa[find(x)] = find(y);
}
void dfs(int root){
    if (v[root].empty())
        ans ++;
    int len = v[root].size();
    for (int i = 0; i < len; i ++){
        dfs(v[root][i]);
    }
}
int main(){
    //ios::sync_with_stdio(false);
    //freopen("text.txt","r",stdin);
    //freopen("out1.txt","w",stdout);
    int n;
    while(cin >> n){
        ans = 0;
        for (int i = 1; i <= n; i ++)
            fa[i] = i, v[i].clear();
        for (int i = 1; i < n; i ++){
            int x, y;
            x = read();
            y = read();
            union_set(y,x);
            v[x].push_back(y);
        }
        int root = find(1);
        dfs(root);
        if (v[root].size() == 1)
            ans ++;
        cout << ans << endl;
    }
    return 0;
}
蹲个大佬,F题看这个代码错哪了?
全部评论

相关推荐

程序员鼠鼠_春招版:我要12k吧我挂了,还招呢,天天被割,这点钱都不舍得出
点赞 评论 收藏
分享
01-26 22:20
已编辑
门头沟学院 Java
Java抽象带篮子:项目很nb了,现在好好准备八股和算法吧,早点找实习,可以看看我的置顶帖子。帖子里写了怎么改简历,怎么包装实习经历,还有2个高质量可速成的项目话术,和我的牛客八股笔记专栏
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务