//传送门: https://www.patest.cn/contests/gplt/L3-015
#include <queue>
#include <functional>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <stack>
#include <vector>
#include <set>
#include <map>
#include <string>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <assert.h>
using namespace std;
/*题意:
就是找一个循环,a赢b,b赢c,…… n再赢a;
值得注意的是 只要 x 在 主场或客场 赢过 y 一次,即可认为 x 赢过 y。
*/
#define N 25
#define M 1000005
char mp[N][N]; //地图,记录胜负关系
bool has[N]; //是否访问过
int last[N]; //若有答案,一次记录谁赢了谁, last[x] = y 代表 x 赢了 y
int n;
bool dfs(int x,int p)
{
if(p==n-1){ //成环要特别判断当前的 x,是否赢过第0支队伍
last[x] = 0;
if(mp[x][0]=='W'||mp[0][x]=='L') return 1;
return 0;
}
bool flag = 0;
for(int i=0;i<n;i++){ // 未访问过的队伍中 是否存在 赢过第0支队伍的队伍
if(has[i]==0&&(mp[i][0]=='W'||mp[0][i]=='L')){
flag = 1;
break;
}
}
if(!flag) return 0; // 不存在,则当前搜索状态无解 (剪枝)
has[x] = 1; // 常规DFS
for(int i=0;i<n;i++){
if(has[i]) continue;
if(mp[x][i]=='W'||mp[i][x]=='L'){
if(dfs(i,p+1)){
last[x] = i;
has[x] = 0;
return 1;
}
}
}
has[x] = 0;
return 0;
}
int main()
{
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%s",mp[i]);
bool flag1 = 0; //若一支队伍没赢过其他队伍,无解
for(int i=0;i<n;i++){
int cot=0;
for(int j=0;j<n;j++){
if(i==j) continue;
if(mp[i][j]=='W'||mp[j][i]=='L') cot++;
}
if(cot) continue;
else{
flag1 = 1; break;
}
if(flag1){
printf("No Solution");
}
bool flag = dfs(0,0); //flag 为 1 表示有解,依据last[] 输出结果
if(flag){
int x = 0;
while(last[x]!=0){
printf("%d ",x+1);
x = last[x];
}
printf("%d",x+1);
}else{
printf("No Solution");
}
return 0;
}
PAT-练习集-L3-015. 球队“食物链”
最新推荐文章于 2021-04-20 20:15:56 发布