1. 程式人生 > >問題 K: WaWa的難題

問題 K: WaWa的難題

問題 K: WaWa的難題

時間限制: 1 Sec  記憶體限制: 128 MB
提交: 570  解決: 125
[提交] [狀態] [命題人:jsu_admin]

題目描述

HaHa和WaWa是好朋友,他們在臨近期末的這段時間一起宅在圖書館學習。
今天HaHa在書上看到一個排列組合題目,思考很久後,仍然找不出其中的規律。
於是他把題目敘述給了WaWa。
題目:
————————————————————————
一個長度為N的排列,由數字1~N組成,它滿足兩個條件。
1、數字1永遠在第一位。
2、任意兩個相鄰數字之差小於等於2。
現在給出一個N,
你能知道能組成多少個符合條件的排列嗎?。
例如:
N=4
1 2 3 4
1 2 4 3
1 3 2 4
1 3 4 2
所以答案為4
————————————————————————
WaWa聽後也是一臉懵逼。
現在WaWa想求助於你們,WaWa給出一個正整數N,問你用1~N能組成多少個符合題意的排列。
 

輸入

多組資料。
每組資料輸入一個正整數N(1<=N<=100)。

輸出

輸出符合題意的排列個數

樣例輸入 Copy

2
4

樣例輸出 Copy

1
4

 

dfs 打表前 10 項即可發現規律

 

a[i]=a[i-1]+a[i-3]+1

 

 

 1 #include<stdio.h>
 2 int num = 0;
 3 int sum = 0;
 4 void dfs(int n,int a){
 5     if(sum == n)
 6     {
 7         num ++;
 8         return ;    
 9     }
10     dfs(n,a++);
11 
12 }
13 int main()
14 {
15     int n;
16     long long a[1000];
17     a[1]=1;
18     a[2]=1;
19     a[3
]=2; 20 a[4]=4; 21 for(int i=5;i<=100;i++) 22 a[i]=a[i-1]+a[i-3]+1; 23 while(scanf("%d",&n)!=EOF) 24 { 25 // num = 0; 26 // dfs(n,1); 27 printf("%lld\n",a[n]); 28 } 29 }
View Code

打表

 1 #include <bits/stdc++.h>
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<cstdlib>
 5 #include<cstring>
 6 #include<cstdio>
 7 #include<string>
 8 #include<vector>
 9 #include<bitset>
10 #include<queue>
11 #include<deque>
12 #include<stack>
13 #include<cmath>
14 #include<list>
15 #include<map>
16 #include<set>
17 //#define DEBUG
18 #define RI register int
19 using namespace std;
20 typedef long long ll;
21 //typedef __int128 lll;
22 const int N=1000;
23 const int MOD=1e9+7;
24 const double PI = acos(-1.0);
25 const double EXP = 1E-8;
26 const int INF = 0x3f3f3f3f;
27 int t,n,m,k,q;
28 int ans=0;
29 int vis[110];
30 void dfs(int x,int c){
31     if(c>=n){
32         ans++;
33         return;
34     }
35     int l=max(1,x-2);
36     int r=min(n,x+2);
37     for(int i=l;i<=r;i++){
38         if(!vis[i]){
39             vis[i]=1;
40             dfs(i,c+1);
41             vis[i]=0;
42         }
43     }
44 }
45 int main()
46 {
47 #ifdef DEBUG
48     freopen("input.in", "r", stdin);
49     //freopen("output.out", "w", stdout);
50 #endif
51     ll a[N];
52     a[1]=1;
53     a[2]=1;
54     a[3]=2;
55     a[4]=4;
56     for(int i=5;i<=100;i++)
57         a[i]=a[i-1]+a[i-3]+1;
58     while(~scanf("%d",&n)){
59         //ans=0;
60         //memset(vis,0,sizeof(vis));
61         //vis[1]=1;
62         //dfs(1,1);
63         cout << a[n] << endl;
64     }
65     //cout << "Hello world!" << endl;
66     return 0;
67 }
View Code