1. 程式人生 > >Graph Theory(思維題)

Graph Theory(思維題)

Graph Theory

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 131072/131072 K (Java/Others)
Total Submission(s): 872    Accepted Submission(s): 415


Problem DescriptionLittle 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 i1).
(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.

InputThe first line of the input contains an integer T
(1T50)
, denoting the number of test cases.
In each test case, there is an integer n(2n100000) in the first line, denoting the number of vertices of the graph.
The following line contains n1 integers a2,a3,...,an(1ai2), denoting the decision on each vertice.
OutputFor each test case, output a string in the first line. If the graph has perfect matching, output ''Yes'', otherwise output ''No''.

Sample Input3212241 1 2Sample OutputYesNoNo

題意:第一行輸入一個整數T

表示測試資料,後面輸入T組資料,一行輸入n表示有n個點。然後進行n-1個操作,1表示能和之前的所有點相連,2就是無操作,問是否能有Perfect match。完美匹配就是線與線無公共點,也就是兩兩相連,無第三條線與其相連。

思路:看懂題目是關鍵,看懂了之後,這道題就很簡單,但是題目極其的難懂,我是一臉懵逼的看完所有描述,我思前想後,比如一個樣例11 2 1 2 1,或許有人會和我之前一樣理解以為最後一個1必須和之前出現的所有數都連一遍,那第一個數就會和後面所有的1都連一遍,那怎麼可能會出現完美匹配。思前想後好久,明白了原來這個1是可以只連一次的,而此時就可能出現完美匹配。說穿了本題就是找兩兩相連,看能不能連完。如果後面出現了一個2,那麼2的後面必須出現一個1與其相連,否則就會有一個沒有相連,或者有公共點。這樣就是2必須對應1,而1可以對應1和2.不得不說題目模糊的一匹,難以理解,真叫人頭禿。

AC程式碼:

#include<bits/stdc++.h>
using namespace std;

#define maxn 100005
int main()
{
    int a[maxn];
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        for(int i=1;i<n;i++)
        {
            scanf("%d",&a[i]);
        }
         int sum=1;
        for(int i=1;i<n;i++)
        {
            if(sum==0) sum++;
            else
            {
                if(a[i]==1) sum--;
                else sum++;
            }
        }
        if(sum!=0) printf("No\n");
        else printf("Yes\n");
    }
}
新手玩家,有心臟類疾病,不喜勿噴。