Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

纪念一下,第一道自己ac的题

Posted by cedricgsh55 at 2019-03-16 11:27:30 on Problem 3126
#include<iostream>
#include<string>
#include<queue>
using namespace std;
int p1, p2;
string s1, s2;
int vis[10000];
struct node
{
	string pri;
	int times;
};
bool isprime(int p)
{
	for (int i = 2; i <= p / i; i++)
		if (p%i == 0)
			return true;
	return false;
}
int bfs()
{
	node p;
	queue<node> arr;
	p.pri = s1;
	p.times = 0;
	arr.push(p);
	while (!arr.empty())
	{
		
		node s = arr.front();
		//cout << s.pri << endl;
		arr.pop();
		if (s.pri == s2)
		{
			return s.times;
		}
		for (int i = 0; i < 4; i++)
		{
			node temp;
			string t;
			t = s.pri;
			if (i == 0)
			{
				for (int j = 1; j <= 9; j++)
				{
					t[i] = j + '0';
					if (!isprime(atoi(t.c_str())) && !vis[atoi(t.c_str())])
					{
						temp.pri = t;
						temp.times = s.times + 1;
						vis[atoi(t.c_str())] = 1;
						arr.push(temp);
					}
				}
			}
			else
			{
				for (int j = 0; j <= 9; j++)
				{
					t[i] = j + '0';
					if (!isprime(atoi(t.c_str())) && !vis[atoi(t.c_str())])
					{
						temp.pri = t;
						temp.times = s.times + 1;
						vis[atoi(t.c_str())] = 1;
						arr.push(temp);
					}
				}
			}
		}
	}
	return -1;
}
int main()
{
	int n;
	cin >> n;
	while (n--)
	{
		memset(vis, 0, sizeof(vis));
		cin >> s1 >> s2;
		p1 = atoi(s1.c_str());
		p2 = atoi(s2.c_str());
		vis[p1] = 1;
		int res = bfs();
		if (res == -1)
			cout << "Impossible" << endl;
		else
			cout << res << endl;
	}
	
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator