【Codeforces 339C】Xenia and Weights
【链接】 我是链接,点我呀:)
【题意】
【题解】
动态规划 设dp[i][j][k]表示第i轮结束之后,左边右边的重量差的绝对值为j,最后一个放的砝码重量为k的情况能否达到 枚举一下每次用哪种砝码(只要不和之前一个状态最后一个用的一样就好)做一下转移即可。 (倒推然后写一个记忆化搜索可能更方便,因为可以直接打印出最后的结果【代码】
import java.io.*;
import java.util.*;
public class Main {
static InputReader in;
static PrintWriter out;
public static void main(String[] args) throws IOException{
//InputStream ins = new FileInputStream("E:\\rush.txt");
InputStream ins = System.in;
in = new InputReader(ins);
out = new PrintWriter(System.out);
//code start from here
new Task().solve(in, out);
out.close();
}
static int N = 10;
static int M = 1000;
static class Task{
String s;
int a[] = new int[N+10],n;
boolean can[][][] = new boolean[M+10][N+10][N+10];
int pre[][][] = new int[M+10][N+10][N+10];
int m;
void dfs(int dep,int delta,int last) {
if (dep==0) return;
int prelast = pre[dep][delta][last];
dfs(dep-1,last-delta,prelast);
out.print(last+" ");
}
public void solve(InputReader in,PrintWriter out) {
s = in.next();
m = in.nextInt();
for (int i = 1;i <= 10;i++)
if (s.charAt(i-1)=='1') {
a[++n] = i;
}
can[0][0][0] = true;
for (int i = 0;i < m;i++)
for (int delta = 0;delta <= N;delta++)
for (int j = 0;j <= N;j++)
if (can[i][delta][j]==true) {
for (int j2 = 1;j2 <= n;j2++)
if (a[j2]>delta && a[j2]!=j) {
can[i+1][a[j2]-delta][a[j2]] = true;
pre[i+1][a[j2]-delta][a[j2]] = j;
}
}
for (int delta = 0;delta <= N;delta++)
for (int j = 0;j <= N;j++)
if (can[m][delta][j]) {
out.println("YES");
dfs(m,delta,j);
return;
}
out.println("NO");
}
}
static class InputReader{
public BufferedReader br;
public StringTokenizer tokenizer;
public InputReader(InputStream ins) {
br = new BufferedReader(new InputStreamReader(ins));
tokenizer = null;
}
public String next(){
while (tokenizer==null || !tokenizer.hasMoreTokens()) {
try {
tokenizer = new StringTokenizer(br.readLine());
}catch(IOException e) {
throw new RuntimeException(e);
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
}
}