Graph Theory

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
 
 
 
题目意思:有n个点,这里给出了n-1个数(第0个点没有操作,所以不用)表示每个点的操作状态,操作1表示当前点与之前出现的所有的点连成一条边,操作2代表什么也不做,问最后是否每一个点都有一个点与其配对(两两配对)。
 
解题思路:英语水平确实太差了,上来看到graph,以为是图论,因为图论的内容没有学习,很打怵,不过榜单上和我水平差不多的队友有做出来的,就明白这不是一道难题,其实这应该算是一道找规律的题,我们很容易知道当n为奇数的时候是不可能出现两两匹配的。当n为偶数时,用count表示前面有多少个未配对的点,如果前面有未配对的点则,若操作为1,,则count--,若操作为2则count++。如果前面所有的点都匹对成功则,若操作为1,,则count=1(因为前面没有点与其配对),若操作为2则count++,最后如果count=0,则说明完美匹配perfect matching。
 
 
 #include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
int main()
{
int t,n,i,count;
int a[];
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
count=;
for(i=; i<n; i++)
{
scanf("%d",&a[i]);
}
if(n%==)
{
printf("No\n");///奇数不可能配对
}
else
{
for(i=; i<n; i++)
{
if(a[i]==)
{
if(count==)
{
count=;
}
else
{
count--;
}
}
else
{
count++;
}
}
if(count==)
{
printf("Yes\n");
}
else
{
printf("No\n");
}
}
}
return ;
}
 看见有大佬写出了这样很简单的代码,我也学习一下:
 
 #include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
int main()
{
int t,n,i,j,a,count;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
count=;
for(i=; i<n; i++)
{
scanf("%d",&a);
if(a==||count==)
{
count++;
}
else
{
count--;
}
}
if(count==)
{
printf("Yes\n");
}
else
{
printf("No\n");
} }
return ;
}
 思路本质上是一样的。。。。。。
 
 
上一篇:The Beginning of the Graph Theory


下一篇:ACM学习历程—NPU1045 2015年陕西省程序设计竞赛网络预赛(热身赛)C题 Graph Theory(递推 && 组合数学 && 大数)