LA3667

题目大意:
给出n种距离di,设计一个有m个刻度的尺子,使得每个di都可以直接量出来,要求在m尽量小的前提下保证尺子总长度尽量短。

思路:
递增暴力搜索

代码:

#include <iostream>
using namespace std;
#include <cstring>
#include <queue>
#include <stdio.h>
#include <algorithm>
#define Maxn 55
#define MAXN 1100000
int d[Maxn],n,ans;
bool vis[Maxn];
int dis[Maxn];
int num[MAXN];

bool dfs(int cur) {
    if(cur == ans) {
        for(int i = 1; i < n; i++)
        if(!vis[i])
            return false;
        return true;
    }
    for(int i = 1; i < cur; i++) {
        for(int j = 1; j < n ; j++) {
            if(!vis[j]) {
                int dd =dis[i] + d[j];
                if(dd <= dis[cur - 1])
                    continue;
                if(dd >= d[n])
                    continue;
                dis[cur] = dd;

                queue<int> Q;
                for(int k = 1; k < cur; k++) {
                    int temp = dis[cur] - dis[k];
                    if(num[temp] && !vis[num[temp]]) {
                        vis[num[temp]] = true;
                        Q.push(num[temp]);
                    }
                }
                int last = d[n] - dis[cur];
                if(num[last] && !vis[num[last]]) {
                    vis[num[last]] = true;
                    Q.push(num[last]);
                }
                if(dfs(cur + 1))
                    return true;
                while(!Q.empty()) {
                    last = Q.front();
                    Q.pop();
                    vis[last] = false;
                }
            }
        }
    }
    return false;按从s[N]到s[1]的顺序来
}
int main() {
    int kases = 1;
    while(scanf("%d",&n)!=EOF && n) {
        for(int i = 1; i <= n; i++)
            scanf("%d",&d[i]);
        sort(d + 1,d + 1 + n);
        n = unique(d + 1, d + 1 + n) - d - 1;
        memset(num,0,sizeof(num));
        for(int i = 1; i <= n; i++) 
            num[d[i]] = i;

        dis[1] = 0;
        ans = 2;
        while(ans *(ans - 1)/2 < n) //最多可以有几个不同的刻度值
            ans++;
        memset(vis,0,sizeof(vis));
        while(!dfs(2))
            ans++;

        printf("Case %d:\n%d\n",kases++,ans);
        printf("%d",dis[1]);
        dis[ans] = d[n];

        for(int i = 2; i <= ans; i++)
            printf(" %d",dis[i]);
        printf("\n");
    }
    return 0;
}

你可能感兴趣的:(LA3667)