uva 140

思路:暴力+剪枝

uva140

wa了好多次……数组开小了……!!!

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <stack>
#include <cctype>
#include <string>
#include <malloc.h>
#include <queue>
#include <map>

using namespace std;
const int INF = 0xffffff;
const double esp = 10e-8;
const double Pi = 4 * atan(1.0);
const int Maxn = 100;
const int mod = 10000007;
const int dr[] = {1,0,-1,0,-1,1,-1,1};
const int dc[] = {0,1,0,-1,1,-1,-1,1};
//int dir2[8][2] = {{-1,0},{0,-1},{-1,1},{1,-1},{-1,-1},{1,0},{0,1},{1,1}};

bool graph[Maxn][Maxn];
int arr[Maxn];
int n;
int Min;
int tot;
bool visit[Maxn];
int ans[Maxn];
int init[Maxn];

void dfs(int cur){
    if(tot >= Min)
        return;
    if(cur == n){
        Min = min(Min,tot);
        for(int i = 0;i < n;i++){
            ans[i] = arr[i];
        }
        return;
    }
    for(int i = 0;i < n;i++){
        if(!visit[ init[i] ]){
            visit[init[i]] = 1;
            arr[cur] = init[i];
            int tmp = 0;
            for(int j = 0;j < cur;j++){
                if(graph[ arr[j] ][ init[i] ]){
                    int tt = abs(cur - j);
                    tmp = max(tmp,tt);
                    if(tmp > Min)
                        break;
                }
            }
            int tt = tot;
            tot = max(tmp,tot);
            dfs(cur+1);
            visit[init[i]] = 0;
            tot = tt;
        }
    }
}
char str[1000];
int main()
{
#ifndef ONLINE_JUDGE
    freopen("inpt.txt","r",stdin);
#endif
    while(scanf("%s",str) != EOF){
        if(str[0] == '#')
            break;
        int len = strlen(str);
        n = 0;
        memset(graph,0,sizeof(graph));
        memset(arr,0,sizeof(arr));
        memset(visit,0,sizeof(visit));
        for(int i = 0;i < len;i++){
            if(str[i] == ' ')
                continue;
            int a = str[i] - 'A';
            if(!arr[a]){
                init[n++] = str[i] - 'A';
                arr[a] = 1;
            }
            for(i = i+1;str[i] != ';' && i < len;i++){
                if(!isalpha(str[i]))
                    continue;
                int b = str[i] - 'A';
                graph[a][b] = 1;
                graph[b][a] = 1;
                if(!arr[b]){
                    init[n++] = str[i] - 'A';
                    arr[b] = 1;
                }
            }
        }
        Min = INF;
        tot = 0;
        sort(init,init+n);
        dfs(0);
        for(int i = 0;i < n;i++){
            printf("%c ",ans[i] + 'A');
        }
        printf("-> %d\n",Min);
    }
    return 0;
}
View Code

 

posted @ 2015-02-10 20:50  寒饼干  阅读(193)  评论(0编辑  收藏  举报