zoukankan      html  css  js  c++  java
  • NYOJ 469 擅长排列的小明 II

    擅长排列的小明 II

    时间限制:1000 ms  |  内存限制:65535 KB
    难度:3
     
    描述

    小明十分聪明,而且十分擅长排列计算。

    有一天小明心血来潮想考考你,他给了你一个正整数n,序列1,2,3,4,5......n满足以下情况的排列:

    1、第一个数必须是1

    2、相邻两个数之差不大于2

    你的任务是给出排列的种数。

     
    输入
    多组数据。每组数据中输入一个正整数n(n<=55).
    输出
    输出种数。
    样例输入
    4
    样例输出
    4
    来源
    Ural
    上传者
    李文鑫


    解题:俺找规律才找出来的,开始写了个暴力搜索,输出前10项结果
    1 1
    2 1
    3 2
    4 4
    5 6
    6 9
    7 14
    8 21
    9 31
    10 46
    找到规律了吧。哈哈

    先上超时代码:
     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <cstdlib>
     5 #include <vector>
     6 #include <climits>
     7 #include <algorithm>
     8 #include <cmath>
     9 #define LL long long
    10 using namespace std;
    11 int d[51],n,cnt;
    12 bool used[51];
    13 void dfs(int cur,int pre){
    14     if(cur > n) {
    15         cnt++;
    16         return;
    17     }
    18     int x = pre-2, y = pre+2;
    19     for(x; x <= y && x <= n; x++){
    20         if(x >= 1 && !used[x]){
    21             used[x] = true;
    22             dfs(cur+1,x);
    23             used[x] = false;
    24         }
    25     }
    26 }
    27 int main(){
    28     while(~scanf("%d",&n)){
    29         cnt = 0;
    30         memset(used,false,sizeof(used));
    31         used[1] = true;
    32         for(int i = 1; i <= n; i++) d[i] = i;
    33         dfs(2,1);
    34         printf("%d
    ",cnt);
    35     }
    36     return 0;
    37 }
    View Code

    AC代码

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <cstring>
     4 #include <cstdlib>
     5 #include <vector>
     6 #include <climits>
     7 #include <algorithm>
     8 #include <cmath>
     9 #define LL long long
    10 using namespace std;
    11 int main(){
    12     int ans[60] = {1,1,1,2,4,6},i;
    13     for(i = 4; i <= 55; i++)
    14         ans[i] = ans[i-1]+ans[i-3]+1;
    15     while(~scanf("%d",&i)) printf("%d
    ",ans[i]);
    16     return 0;
    17 }
    View Code
     
  • 相关阅读:
    分解质因数
    记忆化搜索
    BFS(广度优先搜索)
    DFS(深度优先搜索)
    A*算法
    最小生成树
    最近公共祖先(LCA)问题
    k短路算法
    次短路问题
    拓扑排序
  • 原文地址:https://www.cnblogs.com/crackpotisback/p/3849948.html
Copyright © 2011-2022 走看看