UVA_524_Prime Ring Problem

#include<iostream>
#include<sstream>
#include<string>
#include<vector>
#include<list>
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<algorithm>
#pragma warning(disable:4996)
using std::cin;
using std::cout;
using std::endl;
using std::stringstream;
using std::string;
using std::vector;
using std::list;
using std::pair;
using std::set;
using std::multiset;
using std::map;
using std::multimap;
using std::stack;
using std::queue;
using std::priority_queue;
using std::sort;
using std::next_permutation;
bool isPrime(const int &n)
{
	for (int i = 2; i <= sqrt(n); i++)
	{
		if (!(n%i))
		{
			return false;
		}
	}
	return true;
}
void backtrack(vector<bool>&used,vector<int>&ring,const int &n)
{
	for (size_t i= 2; i!=used.size(); i++)
	{
		if (!used[i]&&isPrime(i+ring[ring.size()-1]))
		{
			used[i] = true;
			ring.push_back(i);
			if (ring.size() == n&&isPrime(1+ring[ring.size()-1]))
			{
				cout << '1';
				for (size_t j = 1; j != ring.size(); j++)
				{
					cout << ' ' << ring[j];
				}
				cout << endl;
			}
			else
			{
				backtrack(used, ring, n);
			}
			ring.pop_back();
			used[i] = false;
		}
	}
}
int main()
{
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	int n,count=0;
	while (cin >> n)
	{
		if (count)
		{
			cout << endl;
		}
		printf("Case %d:\n",++count);
		vector<bool>used(n + 1);
		vector<int>ring{ 1 };
		backtrack(used, ring,n);
	}
	return 0;
}

你可能感兴趣的:(uva,Backtrack)