数字组合 求最大长度

来源:互联网 发布:淘宝如何发布商品 编辑:程序博客网 时间:2024/05/21 14:50


package work;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class AAshuzuhe {
 static int T, N, maxlen;
 static int[][] data;
 static int[] numlen;
 static int conlen[][];
 static boolean[] used;

 public static void main(String[] args) throws FileNotFoundException {
  /* Scanner sc=new Scanner(System.in); */
  Scanner sc = new Scanner(new File("src/lianshu.txt"));
  T = sc.nextInt();
  for (int t = 0; t < T; t++) {
   N = sc.nextInt();
   numlen=new int[N];
   data=new int[N][6];
   conlen=new int[N+1][N+1];
   used=new boolean[N];
   int num;
   int totallen=0;
   for (int i = 0; i < N; i++) {
    num = sc.nextInt();
    ItoA(num, i);
    totallen+=numlen[i];
   }
   for (int i = 0; i < N; i++) {
    for (int j = 0; j < N; j++) {
     if(i!=j){
      fnc(i,j);
     }
    }
   }
   maxlen=0;
   dfs(0,N,0,totallen,N);
   System.out.println(maxlen);
  }
 }

 private static void dfs(int step, int nums, int curlen, int remainlen, int prenum) {
  if(step==nums){return;}
  if(curlen+remainlen-nums+step+1<=maxlen)return;
  for (int i = 0; i < nums; i++) {
   if(!used[i]){
    used[i]=true;
    int tmplen=curlen;
    if(conlen[i][prenum]==0&&step!=0){
     used[i]=false;
     continue;
    }
    curlen+=numlen[i]-conlen[i][prenum];
    if(maxlen<curlen)maxlen=curlen;
    dfs(step+1,nums,curlen,remainlen-numlen[i],i);
    
    used[i]=false;
    curlen=tmplen;
   }
  }
 }

 private static void fnc(int i, int j) {
           for (int len = 1; len <=numlen[i]&&len<=numlen[j] ; len++) {
     int match=1;
     for (int m = numlen[i]-len,n=0; m < numlen[i]&&n<numlen[j]; m++,n++) {
      if(data[i][m]!=data[j][n]){
       match=0;
       break;
      }
     }
     if(match==1){
      conlen[i][j]=len;
      break;
     }
    }
 }

 private static void ItoA(int num, int i) {
  int temp = num;
  int count = 0;
  while (temp > 0) {
   temp = temp / 10;
   count++;
  }
  numlen[i] = count;
  temp=num;
  for (int j = count - 1; j >=0; j--) {
   data[i][j]=temp%10;
   temp=temp/10;
  }
 }
}


、、、

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



、、output

6
3
9
24
46
6
38

0 0
原创粉丝点击