【iHooya】2023年2月1日作业解析
#include <bits/stdc++.h>
using namespace std;
//a存放皇后位置,b标记皇后是否被占用,c,d表示对角线
int a[9], b[9], c[17], d[17];
int sum = 0;
void output()
{
int i;
sum++;
cout << "sum=" << sum << endl;
for (int i = 1; i <= 8; i++)
cout <<<< " " << a[i];
cout << endl;
}
void search(int i)//第i行开始
{
int j;
for (j = 1; j <= 8; j++) //每行的列上有8个皇后可以选择
{
if ((b[j] == 0) && c[i + j] == 0 && (d[i - j + 7]) == 0) //行,列,对角线没有别的皇后
{
a[i] = j; //第i行第j列保存了皇后
b[j] = 1; //第j列被占领了
c[i + j] = 1; //占领对角线
d[i - j + 7] = 1; //占领对角线
if (i == 8)
output();
else
search(i + 1);
b[j] = 0;
c[i + j] = 0;
d[i - j + 7] = 0;
}
}
}
int main()
{
search(1);
return 0;
}
单词排序
输入一行单词序列,相邻单词之间由1个或多个空格间隔,请按照字典序输出这些单词,要求重复的单词只输出一次。(区分大小写)
输入:一行单词序列,最少1个单词,最多100个单词,每个单词长度不超过50,单词之间用至少1个空格间隔。数据不含除字母、空格外的其他字符。
输出:按字典序输出这些单词,重复的单词只输出一次。
样例输入She wants to go to Peking University to study Chinese
样例输出
Chinese
Peking
She
University
go
study
to
wants
分割字符模版不变,对使用sort对动态数组进行排序。
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s;
getline(cin, s);
vector<string> word;//创建string类型动态数组用来存单词
int x = 0;
s = s + ' '; //字符串后加一个空格用做最后一个单词的判断
for (int a = 0; a < s.length(); a++)
{
if (s[a] == ' ') //当遇到空格就说遍历完一个单词了
{
word.push_back(s.substr(x, a - x)); //提取单词放进动态数组中
x = a + 1;
}
}
sort(word.begin(), word.end());
for (int a = 0; a < word.size(); a++)
if ((word[a] != word[a - 1]) && (word[a].empty() != true))
cout << word[a] << endl;
return 0;
}