Given many sticks, the two ends have different colors, and asked if there is such a combination to connect all the sticks to the beginning and end.
Solution: this problem times out when using map to process strings, so I wrote a string hash for interpolation modulo. You only need to determine whether the graph is connected to an odd number or not, and the odd number of vertices cannot appear.
CodeAs follows:
# Include <iostream> # Include <Cstdlib> # Include <Cstring> # Include <Cstdio> # Include <Algorithm> # Include <Map> # Include < String > # Include <Vector>Using STD: vector; typedef unsigned Long Long Int64; Const Int MoD = 250007 ; Const Int64 T = 37 ; Char Sa [ 15 ], Sb [ 15 ]; Int DEG [ 500005 ]; Int Set [ 500005 ]; Int Head [ 250010 ]; Int64 _ POW [ 15 ]; Vector < Int > V; Struct Edge { Int Tag, next; int64 key;} e [ 500005 ]; Int Idx, tag; Int Find ( Int X ){ Return Set [X] = x = Set [X]? X: Find ( Set [X]);} Void Merge (Int A, Int B ){ Set [A] = B ;} Void Insert (int64 key, Int TG ){ Int Pos = Key % MOD; E [idx]. Key = Key; E [idx]. Tag = TG; E [idx]. Next = Head [POS]; head [POS] = Idx ++;} Int64 getkey ( Char STR []) {int64 key = 0 ; Int Len = Strlen (STR ); For ( Int I = 0 ; I <Len; ++ I) {key + = (STR [I]- ' A ' )*_ POW [I];} Return Key ;} Void Hash ( Char STR []) {int64 key = Getkey (STR); insert (Key, tag ++ );} Int Get ( Char STR []) {int64 key = Getkey (STR ); Int Pos = Key %MOD; For ( Int I = head [POS]; I! =- 1 ; I = E [I]. Next ){ If (E [I]. Key = Key ){ Return E [I]. Tag ;}} Return - 1 ;} Int Main (){ Int OK = 0 ; For ( Int I = 0 ; I < 500000 ; ++ I ){ Set [I] = I;} _ POW [ 0 ] = 1 ; For ( Int I = 1 ; I <= 10 ; ++ I) {_ POW [I] = T * _ POW [I- 1 ];} Memset (Head, 0xff , Sizeof (Head )); While (Scanf ( " % S % s " , SA, Sb )! = EOF ){ If (Get (SA) =- 1 ) {Hash (SA );} If ( Get (SB) =- 1 ) {Hash (SB );} Int A = Get (SA), B = Get (SB ); ++ Deg [a], ++ DEG [B]; merge (find (A), find (B ));} For (Int I = 0 ; I <tag; ++ I ){ If ( Set [I] = I ){ ++ OK ;} If (Deg [I] & 1 ) {V. push_back (I );}} If (OK! = 1 && OK) {puts ( " Impossible " ); Return 0 ;} Else If (V. Size ()> 2 ) {Puts ( " Impossible " );} Else {Puts ( " Possible " );} Return 0 ;}