P1019单词接龙-洛谷

版权声明:只要我还活着,我就要凿穿codeforces. https://blog.csdn.net/UnKfrozen/article/details/84863777

P1019单词接龙

题目描述

  单词接龙是一个与我们经常玩的成语接龙相类似的游戏,现在我们已知一组单词,且给定一个开头的字母,要求出以这个字母开头的最长的“龙”(每个单词都最多在“龙”中出现两次),在两个单词相连时,其重合部分合为一部分,例如 beast和astonish,如果接成一条龙则变为beastonish,另外相邻的两部分不能存在包含关系,例如at 和 atide 间不能相连。

输入输出格式

输入格式:
  输入的第一行为一个单独的整数n (n≤20)表示单词数,以下n 行每行有一个单词,输入的最后一行为一个单个字符,表示“龙”开头的字母。你可以假定以此字母开头的“龙”一定存在.
输出格式:
  只需输出以此字母开头的最长的“龙”的长度

输入输出样例

输入样例#1:
5
at
touch
cheat
choose
tact
a
输出样例#1:
23

说明

  连成的“龙”为atoucheatactactouchoose)
  NOIp2000提高组第三题

解析

  挺坑的一道题.给你n个英文单词接龙,

1.重合部分按最小的算,ahh和hha的话,按ahha接起来,而不算aha.
2.查重和是一部分的重合,我之前一直拿单词最后个字母比对.脑抽
3.at不能和atside重合,当然,sideat也不能和at重合.
4.每个单词可以用两次

  用check()函数比对,返回的是最小重合部分,返回0则认为无重合.上图说话2333

#include<iostream>
#include<algorithm>
#include<string>
#include<string.h>
#include<queue>
#include<stdio.h>
#include<stdlib.h>
#ifndef NULL
#define NULL 0
#endif
using namespace std;

struct vec {
	int v;
	string s;
}p[100];
int maxx = 0,n;

int check(string s1, string s2)
{
	int l = s1.length() - 1;
	for (int i = 0; i < min(l,(int) s2.length()-1); i++) {
		bool f = 0;
		for (int j = 0; j <= i; j++)
			if (s1[l - i+j] != s2[j]) {
				f = 1;
				break;
			}
		if (!f)
			return i+1;
	}
	return 0;
}
void dfs(int x,int ans) 
{
	for (int i = 0; i < n; i++) 
		if (p[i].v < 2) {
			int m = check(p[x].s, p[i].s);
			if (m != 0) {
				p[i].v++;
				dfs(i, ans + p[i].s.length()-m);
				p[i].v--;
			}
		}
	maxx = max(maxx, ans);
}
int main()
{
	char c;
	cin >> n;
	for (int i = 0; i < n; i++)
		cin >> p[i].s;
	cin >> c;
	for(int i=0;i<n;i++)
		if (p[i].s[0] == c) {
			p[i].v++;
			int t = p[i].s.length();
			dfs(i, t);
			p[i].v--;
		}
	cout << maxx << endl;
	return 0;
}  

猜你喜欢

转载自blog.csdn.net/UnKfrozen/article/details/84863777