codeforces 402E

首先认识一下01邻接矩阵k次幂的意义:经过k条边(x,y)之间的路径条数
所以可以把矩阵当成邻接矩阵,全是>0的话意味着两两之间都能相连,也就是整个都要在一个强连通分量里,所以直接tarjan染色,如果只有一个色块的话就是YES否则都是NO(其实应该能更简单一些,不过tarjan比较顺手)
还有就是我没仔细看题判了对角巷为0就NO结果WA……

#include<iostream>
#include<cstdio>
using namespace std;
const int N=2005;
int n,h[N],cnt,low[N],dfn[N],tot,s[N],top,col;
bool v[N];
bool f;
struct qwe
{
	int ne,to;
}e[N*N];
int read()
{
	int r=0,f=1;
	char p=getchar();
	while(p>'9'||p<'0')
	{
		if(p=='-')
			f=-1;
		p=getchar();
	}
	while(p>='0'&&p<='9')
	{
		r=r*10+p-48;
		p=getchar();
	}
	return r*f;
}
void add(int u,int v)
{
	cnt++;
	e[cnt].ne=h[u];
	e[cnt].to=v;
	h[u]=cnt;
}
void tarjan(int u)
{
	dfn[u]=low[u]=++tot;
	v[s[++top]=u]=1;
	for(int i=h[u];i;i=e[i].ne)
	{
		if(!dfn[e[i].to])
		{
			tarjan(e[i].to);
			low[u]=min(low[u],low[e[i].to]);
		}
		else if(v[e[i].to])
			low[u]=min(low[u],dfn[e[i].to]);
	}
	if(dfn[u]==low[u])
	{
		col++;
		while(s[top]!=u)
			v[s[top--]]=0;
		v[s[top--]]=0;
	}
}
int main()
{
	n=read();
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
		{
			int x=read();
			if(i!=j&&x)
				add(i,j);
		}
	for(int i=1;i<=n;i++)
		if(!dfn[i])
			tarjan(i);
	if(col==1)
		puts("YES");
	else
		puts("NO");
	return 0;
}
原文地址:https://www.cnblogs.com/lokiii/p/9277076.html