您的位置:首页 > 其它

HDOJ 1116 Play on Words

2015-01-28 07:43 357 查看
题意:给出n个字符串,若一个字符串的最后一个字符与另一个字符串的第一个字符相同,就将两个字符串合并为一个字符串,判断给出的若干个字符串是否能连接成一个字符串。ex:acm+mouse->acmmouse

链接:http://acm.hdu.edu.cn/showproblem.php?pid=1116

思路:欧拉回路问题。将每个单词看作一条有向路径,判断是否满足欧拉回路的条件,并且这些节点是否在同一个集合中。

注意点:无

以下为AC代码:

Run IDSubmit TimeJudge StatusPro.IDExe.TimeExe.MemoryCode Len.LanguageAuthor
128252812015-01-28 07:08:38Accepted1116374MS1212K2548 BG++luminous11
#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <vector>
#include <deque>
#include <list>
#include <cctype>
#include <algorithm>
#include <climits>
#include <queue>
#include <stack>
#include <cmath>
#include <map>
#include <set>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#define ll long long
#define ull unsigned long long
#define all(x) (x).begin(), (x).end()
#define clr(a, v) memset( a , v , sizeof(a) )
#define pb push_back
#define mp make_pair
#define read(f) freopen(f, "r", stdin)
#define write(f) freopen(f, "w", stdout)
using namespace std;
const double pi = acos(-1);
const int maxn = 105;
int buse[30];
int fa[30];
int n;

inline int abs ( const int a ){
return a > 0 ? a : -a;
}

inline int find( int x ){
if ( x == fa[x] )return x;
else return fa[x] = find ( fa[x] );
}

inline void unionfind ( int u, int v ){
int x = find ( u );
int y = find ( v );
if ( x != y )
fa[x] = y;
}

int main()
{
ios::sync_with_stdio( false );
int t;
cin >> t;
while ( t -- ){
cin >> n;
int id[30] = { 0 };
int od[30] = { 0 };
memset ( buse, 0, sizeof ( buse ) );
for ( int i = 0; i < 30; i ++ ){
fa[i] = i;
}
string str;
cin.ignore();
int flag = 1;
for ( int i = 0; i < n; i ++ ){
cin >> str;
int u = str[0] - 'a';
int v = str[str.size()-1] - 'a';
unionfind ( u, v );
buse[u] = buse[v] = 1;
id[v] ++;
od[u] ++;
//cout << v << ' ' << id[v] << "   " << u << ' ' << od[u] << endl;
}
int cnt = 0;
int sum = 0;
int be = -1;
int en = -1;
for ( int i = 0; i < 30; i ++ ){
if ( buse[i] == 0 )continue;
if ( i == fa[i] )cnt ++;
if ( id[i] != od[i] ){
if ( id[i] == od[i] + 1 ) en ++;
else if ( od[i] == id[i] + 1 ) be ++;
else sum ++;
}
//cout << i << ' ' << id[i] << ' ' << od[i] << endl;
}
// cout << cnt << ' ' << be << ' ' << en <<  ' ' << sum << endl;
if ( cnt > 1 || be > 1 || en > 1 || be != en || sum )
flag = 0;
if ( ! flag )
cout << "The door cannot be opened." << endl;
else
cout << "Ordering is possible." << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: