hdu 1181 dfs

一道典型的 dfs(回溯):

使用vector<string>保存单词,sort一下;

dfs的时候,单词的首字母先用二分查找找到上下界,缩小范围;

vis数组:0,1保存状态;


#pragma warning(disable:4996)
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
using namespace std;

vector<string> vec;
bool vis[1000];
bool flag;
char first, last;

int lowBound(char ch)
{
	int low = 0;
	int high = vec.size() - 1;
	while (low <= high)
	{
		int mid = (low + high) / 2;
		if (ch<vec[mid].at(0))
		{
			high = mid - 1;
		}
		else
		{
			low = mid + 1;
		}
	}
	return low;
}

void dfs(char first)
{
	if (first == last)
	{
		flag = 1;
		return;
	}

	int m = lowBound(first - 1);
	int n = lowBound(first + 1);
	for (int i = m; i<n; ++i)
	{
		if (first == vec[i].at(0) && vis[i] == 0)
		{
			char next = vec[i].at(vec[i].size() - 1);
			vis[i] = 1;
			dfs(next);
			vis[i] = 0;
		}
	}
	return;
}

int main()
{
	//freopen("in.txt", "r", stdin);
	string foo;
	while (cin >> foo)
	{
		vec.clear();
		memset(vis, 0, sizeof(vis));
		string zero("0");
		while (foo != zero)
		{
			vec.push_back(foo);
			cin >> foo;
		}
		sort(vec.begin(), vec.end());
		flag = 0;
		first = 'b'; last = 'm';

		dfs(first);

		if (flag)
			cout << "Yes." << endl;
		else
			cout << "No." << endl;
	}
	return 0;
}

你可能感兴趣的:(hdu 1181 dfs)