PAT-练习集-L3-015. 球队“食物链”

//传送门: 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值