题目:乒乓球比赛(武汉大学机试真题):甲={'a','b','c'}、乙={'x','y','z'}两队进行比赛,一直a不和x比,c不和x和z比,请问所有可能的比赛安排
//应该使用全排列 列出所有的比赛结果,再输出满足要求的对局
//但还有一种取巧的方法实现 使用库函数next_Permutation(nums.begin(),nums.end())
int main(){vector<char> teamA={'a','b','c'};//index:0-x,1-y,2-z do{if('a'!=teamA[0]&&'c'!=teamA[0]&&'c'!=teamA[2])cout<<"xyz VS "<<teamA[0]<<teamA[1]<<teamA[2]<<endl;}while(next_permutation(teamA.begin(),teamA.end()));return 0;
}
输出结果:
用回溯法实现全排列,列出所有比赛的可能:
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
vector<int> path;
vector<vector<int>> finalPath;
bool* used = new bool[3];
void backtracking_FullPermutation() {if (path.size() == 3) {finalPath.push_back(path);return;}for (int i = 0; i < 3; i++) {if (!used[i]) {used[i] = true;path.push_back(i);backtracking_FullPermutation();path.pop_back();used[i] = false;}}
}
int main() {//a不打x c不打x,z vector<char> team = { 'x','y','z' };for (int i = 0; i < 3; i++)used[i] = false;backtracking_FullPermutation();for (auto c : finalPath) {if (c[0] != 0 && c[2] != 2 && c[2] != 0)cout << "abc vs " <<team[c[0]] << team[c[1]] << team[c[2]];}return 0;
}