Codeforces 374 C. Travelling Salesman and Special Numbers (dfs、记忆化搜索)

时间:2025-05-02 10:37:37

题目链接:Travelling Salesman and Special Numbers

题意:

  给了一个n×m的图,图里面有'N','I','M','A'四种字符。问图中能构成NIMA这种序列最大个数(连续的,比如说NIMANIMA = 2)为多少,如果有环的话那么最大长度就是无穷。

题解:

  哇,做了这题深深得感觉自己的dfs真的好弱。这题就是从N开始深搜,在深搜的过程中记录值。返回这个值加1.

 //#pragma comment(linker, "/stack:200000000")
//#pragma GCC optimize("Ofast,no-stack-protector")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
//#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
using namespace std;
const int MAX_N = 1e3+;
const int INF = 1e9+;
typedef pair<int,int> P;
char vec[MAX_N][MAX_N];
int mp[MAX_N][MAX_N];
int res[MAX_N][MAX_N];
int vis[MAX_N][MAX_N];
int dir[][] = {-,,,,,,,-};
int ans,flag,N,M,T;
queue<P> que;
vector<P> st;
int dfs(int x,int y,int pos)
{
if(vis[x][y])
{
flag = false; return INF;
}
if(res[x][y]) return res[x][y];
vis[x][y] = ;
int num =;
for(int i=;i<;i++)
{
int nx = x + dir[i][];
int ny = y + dir[i][];
if(nx>= && nx<N && ny>= && ny<M && mp[nx][ny] == (pos+)% )
{
num = max(num,dfs(nx,ny,(pos+)%));
}
}
res[x][y] = num+;
vis[x][y] = ;
return num+;
}
int main()
{
cin>>N>>M;
memset(vis,,sizeof(vis));
memset(res,,sizeof(res));
st.clear();
for(int i=; i<N; i++)
{
scanf("%s",vec[i]);
for(int j=; j<M; j++)
{
if(vec[i][j] == 'D') mp[i][j] = ,st.push_back(P(i,j));
else if(vec[i][j] == 'I') mp[i][j] = ;
else if(vec[i][j] == 'M') mp[i][j] = ;
else if(vec[i][j] == 'A') mp[i][j] = ;
}
}
int out = ;
flag = true;
for(int i=;i<st.size();i++)
{
if(res[st[i].first][st[i].second] != || vis[st[i].first][st[i].second]) continue;
int t = dfs(st[i].first,st[i].second,);
if(!flag) break;
out = max(out,t/);
}
if(flag)
{
if(out != ) cout<<out<<endl;
else cout<<"Poor Dima!"<<endl;
}
else cout<<"Poor Inna!"<<endl;
return ;
}
/*
5 5
DIADD
DMADD
DDDID
AMMMD
MIDAD answer: 3
*/