Graph Theory
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 2353 Accepted Submission(s): 947
Problem 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≤T≤50), denoting the number of test cases.
In each test case, there is an integer n(2≤n≤100000) in the first line, denoting the number of vertices of the graph.
The following line contains n−1 integers a2,a3,...,an(1≤ai≤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''.
题意:对结点2-n,每个点有两个操作,操作1是将结点i与前面所有结点连边,操作2是不连边。定义perfect matching 为一个边集,每一条边没有公共点,且边集中的边包含了所有的结点。给出各个点的操作,问是否有perfect matching。
思路:就是要将点两两配对。首先结点数一定要是偶数,不然是不可能两两配对的。
然后最后一个结点是必须操作1的,不然没有点和最后一个连。
进一步想,每个操作1的点虽然连出去了很多边,但是它只能和它前面的某个点配对
最后,每个操作2的点后面必须有个操作1的点和它配对。也就是说,每个点后面的1数不能少于它之前的2的个数(包括它自己)。写代码的时候愣了。
#include<iostream>
using namespace std;
const int N=1e5+10;
int a[N];
int main()
{
int T;
cin>>T;
while(T--)
{
int n;
cin>>n;
a[1]=2;
for(int i=2;i<=n;++i)
cin>>a[i];
//if(n%2||a[n]==2) //节点个数是奇数或者最后一个没被选
if(n%2)
{
cout<<"No"<<endl;
continue;
}
int cnt=0;
int flag=1;
for(int i=n;i>=1;--i)
{
if(a[i]==1) cnt++;
else if(a[i]==2)
{
cnt--;
if(cnt<0)
{
flag=0;
break;
}
}
}
if(flag) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
return 0;
}