P1118 [USACO06FEB]數字三角形`Backward Digit Su`…
題目描述
FJ
and his cows enjoy playing a mental game. They write down the numbers from 11 to N(1 \le N \le 10)N(1≤N≤10) in a certain order and then sum adjacent numbers to produce a new list with one fewer number. They repeat this until only a single number is left. For example, one instance of the game (when N=4N=4 ) might go like this:
3 1 2 4
4 3 6
7 9
16
Behind FJ
‘s back, the cows have started playing a more difficult game, in which they try to determine the starting sequence from only the final total and the number NN . Unfortunately, the game is a bit above FJ
‘s mental arithmetic capabilities.
Write a program to help FJ
play the game and keep up with the cows.
有這麽一個遊戲:
寫出一個 11 至 NN 的排列 a_iai? ,然後每次將相鄰兩個數相加,構成新的序列,再對新序列進行這樣的操作,顯然每次構成的序列都比上一次的序列長度少 11 ,直到只剩下一個數字位置。下面是一個例子:
3,1,2,43,1,2,4
4,3,64,3,6
7,97,9
1616
最後得到 1616 這樣一個數字。
現在想要倒著玩這樣一個遊戲,如果知道 NN ,知道最後得到的數字的大小 sumsum ,請你求出最初序列 a_iai? ,為 11 至 NN 的一個排列。若答案有多種可能,則輸出字典序最小的那一個。
[color=red]管理員註:本題描述有誤,這裏字典序指的是 1,2,3,4,5,6,7,8,9,10,11,121,2,3,4,5,6,7,8,9,10,11,12
而不是 1,10,11,12,2,3,4,5,6,7,8,91,10,11,12,2,3,4,5,6,7,8,9 [/color]
輸入輸出格式
輸入格式:
兩個正整數 n,sumn,sum 。
輸出格式:
輸出包括 11 行,為字典序最小的那個答案。
當無解的時候,請什麽也不輸出。(好奇葩啊)
輸入輸出樣例
輸入樣例#1:4 16
輸出樣例#1: 3 1 2 4
說明
對於 40\%40% 的數據, n≤7n≤7 ;
對於 80\%80% 的數據, n≤10n≤10 ;
對於 100\%100% 的數據, n≤12,sum≤12345n≤12,sum≤12345 。
Solution:
本題比較水(純暴力就能過)。
不難發現每次合並,每個位置的數所參與的貢獻次數為楊輝三角的第$n$行所對應的數。
舉個例子:$a,b,c,d\rightarrow a+3b+3c+d$。最後一個數中$a,b,c,d$的系數就是楊輝三角第$4$行的數列。
所以我們可以先遞推出前$12$行楊輝三角的數,然後作為系數,因為要使得前面的數值盡可能小,所以就枚舉每一位的取值,隨便加一個可行性剪枝(記錄當前的$tot$,若大於總和$sum$則減掉),然後記錄一下每個數的取值範圍,亂搞一下就好了。
代碼:
1 #include<bits/stdc++.h> 2 #define il inline 3 #define ll long long 4 #define For(i,a,b) for(int (i)=(a);(i)<=(b);(i)++) 5 #define Bor(i,a,b) for(int (i)=(b);(i)>=(a);(i)--) 6 using namespace std; 7 int n,sum,a[15],c[15][15]; 8 bool f=0,vis[15]; 9 10 il int gi(){ 11 int a=0;char x=getchar();bool f=0; 12 while((x<‘0‘||x>‘9‘)&&x!=‘-‘)x=getchar(); 13 if(x==‘-‘)x=getchar(),f=1; 14 while(x>=‘0‘&&x<=‘9‘)a=(a<<3)+(a<<1)+x-48,x=getchar(); 15 return f?-a:a; 16 } 17 18 il void init(){ 19 c[1][1]=1; 20 For(i,2,12) For(j,1,i) c[i][j]=c[i-1][j-1]+c[i-1][j]; 21 } 22 23 il void dfs(int now,int tot){ 24 if(sum-tot<=0)return; 25 if(now==n-1) 26 if(!vis[sum-tot]&&sum-tot<=n) { 27 a[n]=sum-tot; 28 For(i,1,n) cout<<a[i]<<‘ ‘; 29 exit(0); 30 } 31 int p=min(sum-tot,n); 32 For(i,1,p) 33 if(!vis[i]) { 34 a[now+1]=i;vis[i]=1; 35 dfs(now+1,tot+i*c[n][now+1]); 36 vis[i]=0; 37 } 38 } 39 40 int main(){ 41 ios::sync_with_stdio(0); 42 init(); 43 n=gi(),sum=gi(); 44 if(n==1){cout<<1;return 0;} 45 For(i,1,n) { 46 vis[i]=1; 47 a[1]=i,dfs(1,i); 48 vis[i]=0; 49 } 50 return 0; 51 }
P1118 [USACO06FEB]數字三角形`Backward Digit Su`…