优必选笔试三道题

1.根据年月日算星期

  • 记住公式此题无敌
//计算年月日是星期几
int main_ybx111()
{
	int year, month, day;
	while (cin >> year >> month >> day)
	{
		if (month == 1 || month == 2)
		{
			month = month + 12;
			year--;
		}
		int week = (day + 2 * month + 3 * (month + 1) / 5 + year + (year >> 2) - year / 100 + year / 400) % 7 + 1;
		switch (week)
		{
		case 1: {cout << "Monday" << endl; break; }
		case 2: {cout << "Tuesday" << endl; break; }
		case 3: {cout << "Wednesday" << endl; break; }
		case 4: {cout << "Thursday" << endl; break; }
		case 5: {cout << "Friday" << endl; break; }
		case 6: {cout << "Saturday" << endl; break; }
		case 7: {cout << "Sunday" << endl; break; }
		}
	}
	return 0;
}

2.两数的最大公约数

  • 我用的无脑法AC
int main_ybx222()
{
	int num1, num2;
	while (cin >> num1 >> num2)
	{
		if (num1 == 0 || num2 == 0)
		{
			cout << "No result" << endl;
			continue;
		}
		if (num1 == num2)
		{
			cout << "The result is " << num1 << endl;
			continue;
		}
		int maxnum = max(num1, num2);
		int minnum = min(num1, num2);
		int result = minnum;
		bool flag = false;
		do
		{
			if (maxnum % result == 0 && minnum % result == 0)
			{
				cout << "The result is " << result << endl;
				flag = true;
				break;
			}
		} while (result--);
		if (!flag)
			cout << "No result" << endl;
	}

	return 0;
}

3.栈写N皇后

  • 鄙人的第二篇博客就是写的栈写N皇后。。。但是迄今还是没有解决N = 10以上后超市严重的问题,等会解决一下。
class queen
{
public:
	queen(int _x = 0, int _y = 0) : x(_x), y(_y) {}
	bool operator==(const queen &q) const { return (x == q.x) || (y == q.y) || (x + y == q.x + q.y) || (x - y) == (q.x - q.y); }
	bool operator!=(const queen &q) const { return !(*this == q); }
	int x, y;
};

//检验当前栈内有多少位置与当前皇后位置有冲突关系
bool check(stack<queen> temp, queen &qn)
{
	int count = 0;
	while (!temp.empty())
	{
		if (qn == temp.top())
			count++;
		temp.pop();
	}
	return count;
}

int searchNqueen(int N)
{
	int resultnum = 0;
	queen qn(0, 0);
	stack<queen> m_stack;  //栈存储当前列的恍惚
	do
	{
		if (m_stack.size() >= N  || qn.y >= N )
		{
			qn = m_stack.top(); m_stack.pop();
			qn.y++;
		}
		else
		{
			while (qn.y < N && check(m_stack, qn))
			{
				qn.y++;
			}
			if (N > qn.y)
			{
				m_stack.push(qn);
				if (N <= m_stack.size())
					resultnum++;
				qn.x++; 
				qn.y = 0;
			}
		}
	} while (qn.x > 0 || qn.y < N);
	return resultnum;
}

//试探回溯法 栈解决N皇后
int main()
{
	int N;
	while (cin >> N)
	{
		cout << "Total count: " << searchNqueen(N) << endl;
	}

	return 0;
}

你可能感兴趣的:(秋招)