题意:有很多个(以换行还不知什么结尾,反正我判断了'\n' 还有 '\0')颜色,分别是这跟棒子的两端的颜色,然后要让两种想同颜色的可以合并成一根字符串,问的是这些棒子能否串成一根长的大棒子。
然后,我们对于任意一根棒子,都是可以互换端点的,所以这道题就变成了一张无向图,然后无向图求欧拉通路的存在性,岂不是就简单了。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const int maxN = 7e6 + 7, maxE = 5e5 + 7;;
int trie[maxE][26], tot, val[maxN], du[maxN], cnt, fa[maxN];
int fid(int x) { return x == fa[x] ? x : fa[x] = fid(fa[x]); }
inline int Insert(char *s, int len)
{
int root = 0;
for(int i=0, id; i<len; i++)
{
id = s[i] - 'a';
if(!trie[root][id])
{
trie[root][id] = ++tot;
}
root = trie[root][id];
}
if(!val[root]) { val[root] = ++cnt; fa[cnt] = cnt; }
return val[root];
}
int main()
{
char op[25], ts[15];
while(gets(op) && op[0] != '\n' && op[0] != '\0')
{
int i, j, tmp1, tmp2, u, v;
for(i = 0; op[i] != ' '; i++)
{
ts[i] = op[i];
}
ts[i] = '\0';
tmp1 = Insert(ts, i);
du[tmp1]++;
for(j = i + 1; op[j] != '\n' && op[j] != '\0'; j++)
{
ts[j - i - 1] = op[j];
}
ts[j - i - 1] = '\0';
tmp2 = Insert(ts, j - i - 1);
du[tmp2]++;
u = fid(tmp1); v = fid(tmp2);
fa[u] = v;
}
int S = fid(1);
bool flag = true;
for(int i=2; i<=cnt; i++)
{
if(fid(i) != S)
{
flag = false;
break;
}
}
if(!flag) { printf("Impossible\n"); return 0; }
int sum = 0;
for(int i=1; i<=cnt; i++) sum += du[i] & 1;
if(sum == 0 || sum == 2) printf("Possible\n");
else printf("Impossible\n");
return 0;
}
|