SPOJ_PT07Y 图连通问题

1.题面

You are given an unweighted, undirected graph. Write a program to check if it’s a tree topology.

Input

The first line of the input file contains two integers N and M — number of nodes and number of edges in the graph (0 < N <= 10000, 0 <= M <= 20000). Next M lines contain M edges of that graph — Each line contains a pair (u, v) means there is an edge between node u and node v (1 <= u,v <= N).

Output

Print YES if the given graph is a tree, otherwise print NO.

Example

Input:
3 2
1 2
2 3

Output:
YES

2.思路

  • 根据树的定义 e=n-1的连通图 故可将题目转换为图的连通性问题。对于新手我来说,问题分解为:
    • 如何存储图,使用vector实现邻接表
    • 如何判断图的的连通性,采取DFS

3.代码

#include <iostream>
#include <vector>
using namespace std;

int check[10000 + 5];
int n, m;
int counter = 0;

void dfs(vector<int> *node,int i) {
    if (!node[i].size()) return;
    check[i]++;
    counter++;
    for (int k = 0; k < node[i].size(); k++) {
        int temp = node[i][k];
        if(!check[temp])dfs(node,temp);
    }
}

int main() {
    while (cin >> n >> m) {
        int u, v;
        vector<int> node[10000 + 5];
        for (int i = 0; i < m; i++) {
            cin >> u >> v;
            node[u].push_back(v);
            node[v].push_back(u);
        }
        if (m != n - 1) { cout << "NO" << endl; continue; }
        dfs(node,1);
        if (counter != n)   cout << "NO" << endl;
        else cout << "YES" << endl;
        counter = 0;
        for (int i = 0; i < n+1; i++)
            check[i] = 0;
    }
    return 0;
}

4.所得

  • 图的存储有这样几种可能:

    • 邻接矩阵: 遍历时间开销高、稀疏矩阵空间开销大,不考虑存储树
    • 邻接表: 便于存储稀疏矩阵、遍历、查询度数简单、构造繁琐、多重边标记麻烦
    • 邻接多重表:储存边,便于边的增删操作
    • 链式前向星:一般在别的数据结构不能使用时考虑
  • 一种简明的链表前向插入构造:

struct Edge{
    int to,next;
};

Edge E[1010];            
int head[110],Ecou;     

void init()              {
    memset(head,-1,sizeof(head));
    Ecou=0;
}
void addEdge(int u,int v)   {
    E[Ecou].to=v;
    E[Ecou].next=head[u];
    head[u]=Ecou++;
}
  • 图的连通性:
    • 利用非递归DFS再做一遍此题
    • 使用Union Find再做一遍此题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值