import Control.Applicative ((<$>), (<*>)) import Control.Monad (replicateM) import Data.ByteString.Char8 (ByteString) import qualified Data.ByteString.Char8 as B import Data.List (unfoldr, foldl') import Data.Char (isSpace) import Data.Map (Map) import qualified Data.Map as M import Data.IntSet (IntSet) import qualified Data.IntSet as IS main :: IO () main = do [n, m, _] <- f solve n <$> replicateM m f <*> f >>= mapM_ putStrLn where f = readil B.readInt <$> B.getLine solve :: Int -> [[Int]] -> [Int] -> [String] solve n fts fs = let ls = foldl' (g mp) (IS.fromList [1..n]) fs in [(show . IS.size) ls, (unwords . map show . IS.toList) ls] where f mp [a, b, c] = M.insertWith (++) (a, c) [b] (M.insertWith (++) (b, c) [a] mp) mp = foldl' f M.empty fts g mp st d = IS.foldl' h IS.empty st where h s p = case M.lookup (p, d) mp of Just xs -> IS.union s (IS.fromList xs) Nothing -> s readil :: Integral a => (ByteString -> Maybe (a, ByteString)) -> ByteString -> [a] readil f = unfoldr g where g s = do (n, s') <- f s return (n, B.dropWhile isSpace s')