D - Graph Theory

D - Graph Theory
Time Limit:1000MS    Memory Limit:131072KB    64bit IO Format:%I64d & %I64u
use MathJax to parse formulas

Description

Little Q loves playing with different kinds of graphs very much. One day he thought about an interesting category of graphs called ``Cool Graph'', which are generated in the following way:
Let the set of vertices be {1, 2, 3, ..., $n$}. You have to consider every vertice from left to right (i.e. from vertice 2 to $n$). At vertice $i$, you must make one of the following two decisions:
(1) Add edges between this vertex and all the previous vertices (i.e. from vertex 1 to $i-1$).
(2) Not add any edge between this vertex and any of the previous vertices.
In the mathematical discipline of graph theory, a matching in a graph is a set of edges without common vertices. A perfect matching is a matching that each vertice is covered by an edge in the set.
Now Little Q is interested in checking whether a ''Cool Graph'' has perfect matching. Please write a program to help him.
 

Input

The first line of the input contains an integer $T(1\leq T\leq50)$, denoting the number of test cases.
In each test case, there is an integer $n(2\leq n\leq 100000)$ in the first line, denoting the number of vertices of the graph.
The following line contains $n-1$ integers $a_2,a_3,...,a_n(1\leq a_i\leq 2)$, denoting the decision on each vertice.
 

Output

For each test case, output a string in the first line. If the graph has perfect matching, output ''Yes'', otherwise output ''No''.
 

Sample Input

 
     
3 2 1 2 2 4 1 1 2
 

Sample Output

 
     
Yes No No
 

题意:输入t组样例 每组样例先输入一个n 表示下面有n-1个数据 表示第2个到第n个点 每个数据只能是1或2 1代表可以和前面的任意一个点相连 2代表不可以和前面的相连 如果最终每两个点之间有且只有一条线 则输出yes 否则输出n:o
代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <string.h>
using namespace std ;
int a [ 100005 ];
int main ()
{
   
int t , n , b , ans ;
    cin
>> t ;

   
while ( t --)
   
{
       
memset ( a , 0 , sizeof ( a ));     
  cin >> n ;
       
for ( int i = 0 ; i < n -1 ; i ++)
          
scanf ( "%d" ,& a [ i ]);
        ans
= 1 ; //ans赋值为1表示此时没有相连的只有第一个
       
for ( int i = 0 ; i < n -1 ; i ++)
       
{  
         if ( ans == 0 )
                ans
= 1 ; //新的这个没有连上
           
else
           
{
            
               
if ( a [ i ]== 1 )
                    ans
--; //和前面的一个相连
               
else
                    ans
++; //如果a[i]是2 表示没有连上的又多了一个
  
           
}
          

       
}
       
if ( ans == 0 )
           
printf ( "Yes \n " );
       
else
           
printf ( "No \n " );
   
}





   
return 0 ;
}

猜你喜欢

转载自blog.csdn.net/qq_41700151/article/details/80313955