Codeforces Round #197 (Div. 2), problem: (C) Xenia and Weights 【dfs回溯 31ms 100KB】

题意

现有类似砝码的东西,重量在1~10。现在有一个天平,开始两边没东西,现在先往左边,再到右边,又到左边……放砝码。要求每次所放的那一边,重量总和要比另一边大。

求出能满足条件的放砝码的序列。

思路

看当前这步放这个是否满足,满足则继续dfs下去,不满足就枚举下一个

code

#include<bits/stdc++.h>
#define endl '\n'
using namespace std;
char str[20];
int a[20];
int m;
int ans[1100];
int cnt;
bool dfs(int sum,int tot,int pre){
    if(tot==m){
        cout<<"YES"<<endl;
        for(int i=0;i<m-1;i++)
            cout<<ans[i]<<" ";
        cout<<ans[m-1]<<endl;
        return true;
    }
    for(int i=0;i<cnt;i++){
        if(i==pre) continue;
        if((tot&1)&&sum+a[i]>0){ //先放左左边
            ans[tot]=a[i];
            if(dfs(sum+a[i],tot+1,i)) return true;
        }else if(!(tot&1)&&sum-a[i]<0){ //再放右边
            ans[tot]=a[i];
            if(dfs(sum-a[i],tot+1,i)) return true;
        }
    }
    return false;
}
int main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cin>>str>>m;
    cnt=0;
    for(int i=0;i<10;i++)
        if(str[i]=='1') a[cnt++]=i+1;
    if(!dfs(0,0,-1))
    cout<<"NO"<<endl;
    return 0;
}
学如逆水行舟,不进则退
发布了470 篇原创文章 · 获赞 1150 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/weixin_42429718/article/details/104142120