数字接龙
来源:互联网 发布:数据库怎么输入查询 编辑:程序博客网 时间:2024/04/29 13:29
题目:给出N(2~9)个数字,一数尾和另一数头相同可连接,求可连成的最大长度。
数据范围:每数2~6位,每位1~4。
例:123+234=1234 1234+4321=1234321
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ConnectNum2 {
static int n;static int mlen;static boolean[] vis;static int[][] nums;static int[][] canc;public static void main(String[] args) throws FileNotFoundException { // TODO Auto-generated method stub @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); sc = new Scanner(new File("files/connectnum")); int T = sc.nextInt(); for (int t = 0; t < T; t++) { n = sc.nextInt(); nums = new int[n][2]; for (int i = 0; i < n; i++) { nums[i][0] = sc.nextInt(); nums[i][1] = CacuLen(nums[i][0]); } canc = new int[n][n]; for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) { if (i == j) continue; Canconn(i, j); } mlen = 2; for (int i = 0; i < n; i++) { vis = new boolean[n]; vis[i] = true; dfs(i, nums[i][1]); } System.out.println(mlen); }}private static void dfs(int pre, int clen) { // 其实这里本来可以再多加至少两个剪枝,但没什么太大用处, // 因为这个数据量(9个6位数)的复杂度,不是太大,不用剪枝就已经很快, // 而且其中一个需要对nums进行快排,另一个需要传递剩余长度,我不喜欢, // 其实,最主要的原因还是因为我就是这么酷,我就是不写,我不管,我最酷! // (一个傻白甜的微笑的大脸,自己体会) if (clen > mlen) mlen = clen; for (int i = 0; i < n; i++) { if (i == pre || vis[i] || canc[pre][i] == 0) continue; vis[i] = true; dfs(i, clen + nums[i][1] - canc[pre][i]); vis[i] = false; }}private static void Canconn(int n1, int n2) { // TODO Auto-generated method stub int cot = 1; int cot2 = 1; int len = nums[n2][1]; for (int i = 0; i < len; i++) cot2 *= 10; if (nums[n1][1] < nums[n2][1]) len = nums[n1][1]; for (int i = 1; i < len; i++) { cot *= 10; cot2 /= 10; if (nums[n1][0] % cot == nums[n2][0] / cot2) { canc[n1][n2] = i; return; } }}private static int CacuLen(int num) { // TODO Auto-generated method stub if (num / 100000 > 0) return 6; if (num / 10000 > 0) return 5; if (num / 1000 > 0) return 4; if (num / 100 > 0) return 3; if (num / 10 > 0) return 2; return 2;}
}
sample input:
7
3
123
141
234
2
24
123
4
343
2433
2213
3333
8
434121
441
4234
223142
23413
14342
224
234
9
221111
212111
122111
121232
211112
122112
211111
211121
121122
9
123432
123432
123432
123432
123432
123432
123432
123432
123432
9
123412
123412
123412
123412
123412
123412
123412
123412
123412
sample output:
6
3
9
24
46
6
38
0 0
- 数字接龙
- FAFU OJ 数字接龙
- 【fafu】1003 数字接龙(排序意识小谈)
- blog接龙
- 接龙 是什么
- 单词接龙
- 单词接龙
- 单词接龙
- 单词接龙
- 单词接龙
- 接龙游戏
- 单词接龙
- 单词接龙
- 单词接龙
- 单词接龙
- 单词接龙
- 单词接龙
- 接龙游戏
- 创建Lists与Cards
- 1622-5 孔富晨 总结《2016年12月13日》 【连续第74天总结】
- Java自定义JRadioButton(重绘)
- Android布局优化之使用style提取重复使用属性
- 浅析HTMl5中的Web Storage:sessionStorage和localStorage
- 数字接龙
- Mybatis中用OGNL表达式处理动态sql
- [Canvas系列]Canvas填充与渐变_03
- bootstrap时间插件
- 遍历几种常见格式的json、AJAX和json
- Cassandra 设计模式(第二版)_前言
- 《C++ Primer Plus(第六版)》(11)(第八章 函数探幽 复习题答案)
- Android开发 安卓中常用设计模式总结
- 使用注解配置spring中的aop