sicily 1021&1932. Couples

Description
N couples are standing in a circle, numbered consecutively clockwise from 1 to 2N. Husband and wife do not always stand together. We remove the couples who stand together until the circle is empty or we can't remove a couple any more. Can we remove all the couples out of the circle?

Input
 There are multiple test cases. The first line contains an integer T, indicating the number of test cases. In each case, the first line is an integer N(1 <= N <= 100000)----the number of couples. In the following N lines, each line contains two integers ---- the numbers of each couple.

Output
 Output "Yes" if we can remove all the couples out of the circle. Otherwise, output "No".

第一次用栈写东西。为了增强可利用性,对栈的操作全部通过专用函数完成,有一点啰嗦。照抄一下实验报告的心得,有空再写带图的题解吧……

如果一个用例中的couple可以全部移走,则将环拆成链后最后的一对couple依然相邻,可以全部移走,因此将环拆成一个链来解决不影响结果;
内部解决过程类似于用栈和编号的匹配来模拟一个不能弹射的泡泡龙,若栈空则将匹配编号压栈等待匹配(泡泡的积累),若栈顶元素与遍历到的编号匹配则弹栈(泡泡的消去),若不匹配也压栈(泡泡的积累)

 AC runtime 0.06sec,效率还不错

View Code
 1 #include<stdio.h>
 2 #include<memory.h>
 3 
 4 int couple[100010] = {0};
 5 int stack[200010] = {0};
 6 int top = 0;
 7 
 8 int is_stack_empty( void );
 9 void stack_push( int num );
10 void stack_pop( void );
11 int stack_top( void );
12 int match( int n );
13 
14 int main()
15 {
16     int n;
17     int husb, wife;
18     int i;
19 
20     while( scanf("%d", &n) && n != 0 )
21     {
22         memset( stack, 0, sizeof(stack) );
23         memset( couple, 0, sizeof(couple) );
24         top = 0;
25         
26         for ( i = 1; i <= n; i++ )
27         {
28             scanf( "%d %d", &husb, &wife );
29             couple[husb] = wife;
30             couple[wife] = husb;
31         }
32         
33         printf( match(n) ? "Yes\n" : "No\n" );
34     }
35     
36     return 0;
37 }
38 
39 int is_stack_empty( void )
40 {
41     if ( top == 0 )
42     {
43         return 1;
44     }
45     else
46     {
47         return 0;
48     }
49 } 
50 
51 void stack_push( int num )
52 {
53     top++;
54     stack[top] = num; 
55 }
56 
57 void stack_pop( void )
58 {
59     stack[top] = 0;
60     top--;
61 }
62 
63 int stack_top( void )
64 {
65     return stack[top];
66 }
67 
68 int match( int n )
69 {
70     int i;
71     
72     for( i = 1; i <= 2 * n; i++ )
73     {
74         if( is_stack_empty() || i != couple[stack_top()] )
75         {
76              stack_push(i);
77         }
78         else
79         {
80             stack_pop();
81         }
82     }
83     
84     return( is_stack_empty() ? 1 : 0 );
85 }
原文地址:https://www.cnblogs.com/joyeecheung/p/2813529.html