POJ 2513 Colored Sticks
2016-07-17 09:33
363 查看
Description
You are given a bunch of wooden sticks. Each endpoint of each stick is colored with some color. Is it possible to align the sticks in a straight line such that the colors of the endpoints that touch are of the same color?
【题目分析】
这道题还是比较综合的,hash用map太慢,用普通的trie树节点过多,左儿子、右兄弟又太慢。于是遇到了这种带指针的trie,比较简单而且方便。
人生第一份带指针的代码
【代码】
You are given a bunch of wooden sticks. Each endpoint of each stick is colored with some color. Is it possible to align the sticks in a straight line such that the colors of the endpoints that touch are of the same color?
【题目分析】
这道题还是比较综合的,hash用map太慢,用普通的trie树节点过多,左儿子、右兄弟又太慢。于是遇到了这种带指针的trie,比较简单而且方便。
人生第一份带指针的代码
【代码】
#include <cstdio> #include <cstring> int f[500001],rank[500001],deg[500001],n; struct trie { int color; trie *next[26]; trie() { color=0; memset(next,0,sizeof (next)); } }*root; int insert(trie *p,char str[]) { int i; for (i=0;str[i]!='\0';++i) { int s=str[i]-'a'; if (p->next[s]==NULL) p->next[s]=new trie; p=p->next[s]; if (str[i+1]=='\0') { if (p->color==0) p->color=++n; deg[p->color]++; } } return p->color; } inline void init() {for (int i=1;i<=50000;++i) f[i]=i;} inline int gf(int k) { if (f[k]==k) return k; else return f[k]=gf(f[k]); } inline void un(int a,int b) { int fa=gf(a),fb=gf(b); if (fa==fb) return ; f[fa]=fb; } inline void read() { char s1[11],s2[11]; int x,y; n=0,root=new trie; init(); while (~scanf("%s%s",s1,s2)) { x=insert(root,s1); y=insert(root,s2); un(x,y); } } inline bool cal() { int flag=0; for (int i=1;i<=n;++i) { if (flag&&f[i]==i) return false; if (f[i]==i) flag=1; } int x=0; for (int i=1;i<=n;++i) if (deg[i]%2) x++; if (x==0||x==2) return true; return false; } int main() { read(); if (cal()) printf("Possible\n"); else printf("Impossible\n"); }
相关文章推荐
- 初学ACM - 组合数学基础题目PKU 1833
- POJ ACM 1001
- POJ ACM 1002
- 1611:The Suspects
- POJ1089 区间合并
- POJ 2159 Ancient Cipher
- POJ 2635 The Embarrassed Cryptographe
- POJ 3292 Semi-prime H-numbers
- POJ 2773 HAPPY 2006
- POJ 3090 Visible Lattice Points
- POJ-2409-Let it Bead&&NYOJ-280-LK的项链
- POJ-1695-Magazine Delivery-dp
- POJ1523 SPF dfs
- POJ-1001 求高精度幂-大数乘法系列
- POJ-1003 Hangover
- POJ-1004 Financial Management
- [数论]poj2635__The Embarrassed Cryptographer
- [二分图匹配]poj2446__Chessboard
- POJ1050 最大子矩阵和
- 用单调栈解决最大连续矩形面积问题