B. A Tide of Riverscape

 

http://codeforces.com/contest/989/problem/B

 

思路还是从模拟开始。设前p个字符为p串,遍历p串的所有情况,然后对于剩下的字符,检查是否满足题目要求

1、p串有2^2000种可能,数组保存不下所有情况,于是考虑深搜,也就是遇到'.',直接假设为0考虑下一个,不行的话函数返回考虑'1'

2、对于例子2,我们发现p的长度可以更短,当p很大,如n=2000,p=1500,p里就会出现很多并不影响结果但又需要深搜的字符,事实上,只有前min=Math.min(n-p,p)个字符是有检查机会的

 

 1 public class Main {
 2     static int n, p, min,find;
 3     static String s;
 4 
 5     public static void main(String[] args) {
 6         Scanner io = new Scanner(System.in);
 7 
 8         n = io.nextInt();
 9         p = io.nextInt();
10         s = io.nextLine();
11         while (s.length() == 0) s = io.nextLine();
12 
13         min = Math.min(p, n - p);
14 
15         d(0,"");
16         if (find==0)System.out.println("No");
17     }
18     
19     //find保证只打印一个结果
20     static void d(int depth, String ss) {
21         if (find==1)return;
22         if (depth == min) {
23             StringBuilder s0 = new StringBuilder(ss + s.substring(min));
24 
25             OUT:
26             //遍历p串的每一个字符,检查对应位是否有不一样的,只要有就输出结果
27             for (int i = 0; i < min; i++) {
28                 char ch = s0.charAt(i);
29                 //遍历对应位
30                 for (int j = i + p; j < s0.length(); j += p) {
31                     //有不一样的,输出结果
32                     if (s0.charAt(j) != ch) {
33                         if (s0.charAt(j) == '.') {
34                             if (ch == '0') s0.replace(j, j + 1, "1");
35                             else s0.replace(j, j + 1, "0");
36                         }
37                         for (int l = 0; l < s0.length(); l++) if (s0.charAt(l) == '.') s0.replace(l, l + 1, "0");
38                         System.out.println(s0.toString());
39                         find=1;
40                         return;
41                     }
42                 }
43             }
44             return;
45         }
46         if (s.charAt(depth)!='.')d(depth+1,ss+s.charAt(depth));
47         else {
48             d(depth+1,ss+"0");
49             d(depth+1,ss+"1");
50         }
51     }
52 }
原文地址:https://www.cnblogs.com/towerbird/p/11242674.html