[DFS]poj1416

題意:
輸入整數串,然後計算分割成小於等於Target的最大的和

如果輸入的串分割後的和最小都比Target大,那就輸出error.
如果有多種結果一樣,那麼就輸出rejected.
否則,輸出最大的和 和分別是哪些子串。

這個題都是整數,所以比較簡單。

直接搜索所有的情況就好了,還有一點是打印路徑,一般可以用path[]或者pre[]的數組表示,但是這裏數據有點大我就用的map水過了。。

#include <cstdio>
#include <cstring>
#include <cmath>
#include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <algorithm>
#define read freopen("q.in","r",stdin)
#define LL long long
#define maxn 10000000
using namespace std;
int t,a;
int flag,res,kk;
map<int,int> pre;
int pow(int x,int n)
{
    int res=1;
    for(int i=0;i<n;i++)
    {
        res*=x;
    }
    return res;
}
void dfs(int x,int s,int k,int d)
{
    if(s>t)return ;
    if(x==0)
    {
        if(res==s)flag=1;
        else if(s>res && s<=t)
        {
            kk=d;
            res=s;
            flag=0;
        }
        return ;
    }
    int i,j,cnt=0;
    int tmp=x;
    int b[10];
    while(tmp)
    {
        b[cnt++]=tmp%10;
        tmp/=10;
      // cout<<b[cnt-1]<<" ";
    }
   //cout<<endl;
    tmp=0;
    j=1;
    for(i=0;i<cnt;i++,j++)
    {
        tmp+=(b[i]*(pow(10,j-1)));
        pre[s+tmp]=s;
        dfs(x/(pow(10,j)),s+tmp,tmp,d+1);
    }
    return ;
}
bool check()
{
    int tmp=a,res=0;
    while(tmp)
    {
        res+=(tmp%10);
        tmp/=10;
    }
    return res>t;
}
int main()
{
   // read;
    while(~scanf("%d%d",&t,&a) && t+a)
    {
        if(t==a)
        {
            cout<<a<<" "<<a<<endl;
            continue;
        }
        else if(check())
        {
            cout<<"error"<<endl;
            continue;
        }
        res=0;
        flag=0;kk=0;
        dfs(a,0,0,0);
        if(flag)cout<<"rejected"<<endl;
        else
        {
            cout<<res;
            for(int i=0;i<kk;i++)
            {
                cout<<" "<<res-pre[res];
                res=pre[res];
            }


            cout<<endl;

        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章