codeforces 459C - Pashmak and Buses 【構造題】

來源:互聯網
上載者:User

標籤: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;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.