有人说这题纯 d f s dfs dfs可过?实测会 W A / T L E WA/TLE WA/TLE。。。
然后尝试一下改成 b f s bfs bfs,还是 W A WA WA了QwQ
显然两种做法都有人hack了。(此题 O ( n ) O(n) O(n)解法都是错的)
那么我们把两种方法一起跑一遍。
A了???WTF
简单说一下做法。
用
d
f
s
dfs
dfs和
b
f
s
bfs
bfs分别求生成树。如果中途发现一个点与它的爷爷有边,直接输出并exit(0)
。。。
然后如果还担心被hack可以随机一下边表。
考试的时候这题要卡常,所以用二维数组前向星了。
#include<cstdio>
#include<cstdlib>
#include<queue>
using namespace std;
char gc()
{
static char buf[1<<18],*p1=buf,*p2=buf;
if(p1==p2)
{
p2=(p1=buf)+fread(buf,1,1<<18,stdin);
if(p1==p2)
{
return EOF;
}
}
return *p1++;
}
//#define gc getchar
template<typename _Tp>
void read(_Tp& x)
{
x=0;
char c=gc();
while(c<'0'||c>'9')c=gc();
while(c>='0'&&c<='9')x=(x<<1)+(x<<3)+(c^48),c=gc();
}
int n;
bool vis[5005];
short G[5005][5005];
short tot[5005];
short fa[5005];
short top=2;
void dfs(int u)
{
if(vis[u])return;
vis[u]=1;
for(int i=0;i<tot[u];++i)
{
int v=G[u][i];
if(vis[v])
{
if(fa[fa[u]]==v)
{
printf("%d %d %d",fa[fa[u]],fa[u],u);
exit(0);
}
continue;
}
fa[v]=u;
dfs(v);
}
}
void bfs(int s)
{
queue<int> q;
q.push(s);
vis[s]=1;
while(!q.empty())
{
int u=q.front();
for(int i=0;i<tot[u];++i)
{
int v=G[u][i];
if(vis[v])
{
if(fa[fa[u]]==v)
{
printf("%d %d %d",fa[fa[u]],fa[u],u);
exit(0);
}
continue;
}
fa[v]=u;
vis[v]=1;
q.push(v);
}
q.pop();
}
}
int main()
{
read(n);
for(int i=1;i<=n;++i)
{
for(int j=1;j<=n;++j)
{
char c=gc();
while(c!='0'&&c!='1')c=gc();
if(c&1)
{
G[i][tot[i]++]=j;
}
}
}
for(int i=1;i<=n;++i)dfs(i);
for(int i=1;i<=n;++i)vis[i]=0;
for(int i=1;i<=n;++i)bfs(i);
puts("-1");
}
此方法适用于任意图,当心被卡就是了。。。