题目连接:http://acm.hdu.edu.cn/showproblem.php?pid=5961
OK
——————————————————————————————————————————————————————————
题解:
bfs有时也是很好用的。
解题思路:
解题思路:
题目最重要的一句话,如下图.
只有a->b,b->c,一定存在a->c,那么就很容易处理了,只要把a连接的所有点标记掉,那如果图是传递的,就不存在其他点能通过a连接的点到达,反之图就不是传递的,即如果bfs搜到了长度超过1的路径,就意味着图不是传递的。
代码如下:
1 #include <cstdio> 2 #include <cstring> 3 #include <iostream> 4 #include <algorithm> 5 #include <queue> 6 using namespace std; 7 const int maxn=2020; 8 struct Edge{ 9 int from,to,nex; 10 }p[maxn*maxn],q[maxn*maxn]; 11 int ans,cnt; 12 int headp[maxn],headq[maxn]; 13 int vis[maxn]; 14 char s[maxn]; 15 struct node{ 16 int num,sum; 17 }now; 18 bool flag; 19 int n; 20 void bfs(){ 21 for(int i=0;i<n;i++){ 22 if(headp[i]!=-1){ 23 memset(vis,0,sizeof(vis)); 24 queue<node>que; 25 que.push(node{i,0}); 26 while(!que.empty()){ 27 now=que.front(); 28 que.pop(); 29 if(now.sum>=2){ 30 flag=false; 31 return; 32 } 33 for(int j=headp[now.num];j!=-1;j=p[j].nex){ 34 if(vis[p[j].to]==0){ 35 vis[p[j].to]=1; 36 que.push(node{p[j].to,now.sum+1}); 37 } 38 } 39 } 40 } 41 } 42 } 43 void bfs1(){ 44 for(int i=0;i<n;i++){ 45 if(headq[i]!=-1){ 46 memset(vis,0,sizeof(vis)); 47 queue<node>que; 48 que.push(node{i,0}); 49 while(!que.empty()){ 50 now=que.front(); 51 que.pop(); 52 if(now.sum>=2){ 53 flag=false; 54 return; 55 } 56 for(int j=headq[now.num];j!=-1;j=q[j].nex){ 57 if(vis[q[j].to]==0){ 58 vis[q[j].to]=1; 59 que.push(node{q[j].to,now.sum+1}); 60 } 61 } 62 } 63 } 64 } 65 } 66 int main(){ 67 //freopen("a.in","r",stdin); 68 int t;scanf("%d",&t); 69 while(t--){ 70 scanf("%d",&n); 71 cnt=1,ans=1; 72 memset(headp,-1,sizeof(headp)); 73 memset(headq,-1,sizeof(headq)); 74 for(int i=0;i<n;i++){ 75 scanf("%s",s); 76 for(int j=0;j<n;j++){ 77 if(s[j]=='P'){ 78 p[cnt].from=i; 79 p[cnt].to=j; 80 p[cnt].nex=headp[i]; 81 headp[i]=cnt++; 82 }else if(s[j]=='Q'){ 83 q[ans].from=i; 84 q[ans].to=j; 85 q[ans].nex=headq[i]; 86 headq[i]=ans++; 87 } 88 } 89 } 90 flag=true; 91 bfs(); 92 if(flag)bfs1(); 93 if(flag)printf("T\n"); 94 else printf("N\n"); 95 } 96 return 0; 97 }