题意:给定两个人的起始位置,每人走一步,直到不能走,问最后谁赢。每个人走的必须比另一个人大。
解题思路:很容易想到深搜,深搜的过程可以记忆化一下,不然会超时。用dp[i][j][last]代表,A在i,B在j,A走,A选择走的路的大小为last的胜者是谁。1为胜者为A,2为胜者为B。这样子记忆化搜索即可。
#include <iostream>
#include <string>
#include <algorithm>
#include <map>
#include <memory.h>
using namespace std;
int n,m;
char G[105][105];
int dp[105][105][30];
int dfs(int u,int v,int last){
if(dp[u][v][last])
return dp[u][v][last];
//遍历每一条路
for(int i=1;i<=n;i++){
if(G[u][i]-'a'>=last)
{
//注意,这里的B为i,因为要交替的走
int win=dfs(v,i,G[u][i]-'a');
if(win==2)//后者赢的话,在递归前是前者赢
return dp[u][v][G[u][i]-'a']=1;
}
}
return dp[u][v][last]=2;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
int u,v;
char c[2];
memset(G,0,sizeof G);
memset(dp,0,sizeof dp);
for(int i=0;i<m;i++)
{
scanf("%d%d%s",&u,&v,c);
G[u][v]=c[0];
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
//搜索每一个答案
if(dfs(i,j,0)==1) printf("A");
else printf("B");
}
printf("\n");
}
}
return 0;
}