Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

回溯+剪枝G++94ms水过,贴个代码

Posted by uuuouou at 2014-09-28 00:39:54 on Problem 1239
#include <cstring>
#include <cstdio>
#include <vector>
using namespace std;

struct NumberString{
    const char* s;
    int len;
    int compare(const NumberString& other)const{
        int i = 0, j = 0;
        for(; s[i] == '0' && i < len; ++i) ;
        for(; other.s[j] == '0' && j < other.len; ++j) ;
        if(len - i > other.len - j) return 1;
        else if(len - i < other.len - j) return -1;
        else return strncmp(s+i, other.s+j, len-i);
    }
    void print()const{
        for(int i = 0; i < len; ++i) putchar(s[i]);
    }
};
bool betterThan(const vector<NumberString>& a, const vector<NumberString>& b)
{
    if(b.empty()) return true;
    
    int res = a.back().compare(b.back()), i = 0;
    if(res < 0) return true;
    if(res > 0) return false;
    for(; i < a.size() && i < b.size(); ++i){
        res = a[i].compare(b[i]);
        if(res > 0) return true;
        if(res < 0) return false;
    }
    return i < a.size();
}

vector<NumberString> v, r;
void split(const char* s, int i)
{
    if(!s[i]){
        if(betterThan(v, r)) r = v;
        return;
    }
    
    int j = i;
    for(; s[j] == '0'; ++j) ;
    if(!s[j]) return;
    
    NumberString num;
    if(!v.empty()){
        int k = j;
        for(; s[k]; ++k){
            num.s = s + j;
            num.len = k - j + 1;
            if(num.compare(v.back()) > 0) break;
        }
        if(!s[k]) return;
        j = k;
    }
    for(; s[j]; ++j){
        num.s = s + i;
        num.len = j - i + 1;
        if(!r.empty() && num.compare(r.back()) > 0){//strong cut!!!
            break;
        }
        v.push_back(num);
        split(s, j+1);
        v.pop_back();
    }
}

int main()
{
    char s[100];
    while(scanf("%s", s), s[1] || s[0] != '0'){
        v.clear();
        r.clear();
        split(s, 0);
        if(r.empty()) puts(s);
        else{
            for(int i = 0; i < r.size(); ++i){
                if(i) putchar(',');
                r[i].print();
            }
            putchar('\n');
        }
    }
    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator