標籤:python algorithm 數學 iterator map
題目:codeforces 459C - Pashmak and Buses
題意:給出n個人,然後k輛車,d天時間,然後每天讓n個人選擇坐一輛車去上學,要去d天不能有任意兩個人乘同一輛車,不能的話輸出 -1
分類:數學,構造
分析:這個題目首先得分析,我開始想到的是首先用相同的放在一起,比如 7 2 3
這樣構造 1 1 1 1 2 2 2
1 1 1 2 2 2 1
1 1 2 2 2 1 1
1 2 2 2 1 1 1
就是需要的天數跟每一行出現次數最多的數的出現次數相等,但是發現還有更優的方法,可以找到最多次數-1的方案
這樣構造1 2 1 2 1 2 1
1 1 2 2 1 1 2
1 1 1 1 2 2 2
那麼是怎樣得到的呢?
這其實可以用構造數的原理,我們把每一列從下往上看成一個 k 進位的長度為 d 的數,然後構造這樣的 n 個數就好了,其實很簡單,直接從0開始枚舉到n-1,然後每個數+1,就是結果。
那麼判斷不滿足條件的就很簡單了,k^d < n 的話,肯定沒辦法構造出來,注意會超int
當然可以用深搜來枚舉所有可能的情況,來構造,方法差不多
代碼:python
n,k,d = map(int,raw_input().split())if(n> k**d): print -1else: ans = [] for i in range(n): tmp = i; cur = [] for j in range(d): cur.append(tmp%k+1) tmp/=k ans.append(cur) for i in range(d): for j in ans: print j[i], #沒有換行輸出 print ('\n')
c++
#include <cstdio>#include <cstring>#include <string>#include <queue>#include <stack>#include <map>#include <vector>#include <iostream>#include <algorithm>#include <cmath>#include <set>#include <utility>#define Del(a,b) memset(a,b,sizeof(a))const int N = 1200;using namespace std;int a[N][N];int main(){ int n,k,d; while(~scanf("%d%d%d",&n,&k,&d)) { if(double(n)>pow((double)k,d)) printf("-1\n"); else { Del(a,0); for(int st=0;st<n;st++) { int tmp=st,j=0; while(tmp) { a[j][st]=tmp%k; tmp/=k;j++; } } for(int i=0;i<d;i++) { for(int j=0;j<n;j++) { printf("%d%c",a[i][j]+1,j==n?'\n':' '); } printf("\n"); } } } return 0;}