BestCoder Round #53 (div.2) C.Rikka with Graph II(dfs)


分析:dfs。找到度数为 1 的点,跑一遍dfs得到最大距离,如果等于 n 则可行,否则不可行。如果度数为 1 的点超过两个,则不可行。

题目链接:http://bestcoder.hdu.edu.cn/contests/contest_chineseproblem.php?cid=625&pid=1003

代码清单:

/*******************************************************************************
 *** problem ID  : HDU_5424.cpp
 *** create time : Wed Dec 09 17:25:48 2015
 *** author name : nndxy
 *** author blog : http://blog.csdn.net/jhgkjhg_ugtdk77
 *** author motto: never loose enthusiasm for life, life is to keep on fighting!
 *******************************************************************************/

#include <map>
#include <set>
#include <cmath>
#include <queue>
#include <stack>
#include <ctime>
#include <vector>
#include <cctype>
#include <string>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>

using namespace std;

#define exit() return 0
#define setIn(name) freopen(name".in", "r", stdin)
#define setOut(name) freopen(name".out", "w", stdout)
#define debug(x) cout << #x << " = " << x << endl

typedef long long ll;
typedef unsigned int uint;
typedef unsigned long long ull;

const int maxn = 1000 + 5;

int n;
int a, b;
int id, sum;
bool vis[maxn], ok;
bool tmap[maxn][maxn];
vector <int> graph[maxn];
int degree[maxn];

void input() {

	for(int i = 1; i <= n; i++) graph[i].clear();
	memset(tmap, false, sizeof(tmap));
	memset(degree, 0, sizeof(degree));

	for(int i = 1; i <= n; i++) {
		scanf("%d%d", &a, &b);
		if(a == b || tmap[a][b]) continue;
		graph[a].push_back(b);
		graph[b].push_back(a);
		tmap[a][b] = tmap[b][a] = true;
		degree[a]++; degree[b]++;
	}
}

bool dfs(int u, int len) {
	if(len == n) return true;
	for(int i = 0; i < graph[u].size(); i++) {
		int v = graph[u][i];
		if(!vis[v]) {
			vis[v] = true;
			if(dfs(v, len+1)) return true;
			vis[v] = false;
		}
	}return false;
}

bool work() { 

	memset(vis, false, sizeof(vis));
	id = 1; sum = 0;
	for(int i = 1; i <= n; i++) {
		if(degree[i] == 1) {
			id = i;
			sum++;
		}
	}
	if(sum > 2) return false;
	vis[id] = true;
	return dfs(id, 1);
}

void solve() {
	if(work()) puts("YES");
	else puts("NO");
}

int main() {
	//setIn("in");
	while(scanf("%d", &n) != EOF) {
		input();
		solve();
	}   exit();
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值