USACO算法序列四十九——latin

   题目:http://www.nocow.cn/index.php/Translate:USACO/latin

   题目大意为,矩阵的魔幻变化,我采用模拟的方法,结果超时了。晚上再想想吧。好久没做USACO了,还剩最后几道题,加油啊!

#include<iostream> #include <fstream> #define SIZE 8 using namespace std; ifstream fin("latin.in"); ofstream fout("latin.out"); int row[SIZE][SIZE] = {0}; int col[SIZE][SIZE] = {0}; int n=0; long long result = 0; //读取并初始化数据 void read() { fin >> n; for (int i=1; i <= n; i ++) { row[1][i] = 1; row[i][i] = 1; col[1][i] = 1; col[i][i] = 1; }//end for i }//end read void latin(int r, int c) { if (r >= n) { result ++; return; }//end r if (c > n) { latin(r+1, 2); return; }//end c for (int i =1; i <= n; i ++) { if (row[r][i] != 1 && col[c][i] != 1) { row[r][i] = 1; col[c][i] = 1; latin(r, c + 1); row[r][i] = 0; col[c][i] = 0; }//end if }//end for } void print() { for (int i=2; i < n; i ++) { result *= i; } fout << result << endl; } int main() { read(); latin(2,2); print(); return 0; }

    运行效果如下:

Executing... Test 1: TEST OK [0.000 secs, 3020 KB] Test 2: TEST OK [0.000 secs, 3020 KB] Test 3: TEST OK [0.000 secs, 3020 KB] Test 4: TEST OK [0.000 secs, 3020 KB] Test 5: TEST OK [0.000 secs, 3020 KB] > Run 6: Execution error: Your program (`latin') used more than the allotted runtime of 1 seconds (it ended or was stopped at 1.674 seconds) when presented with test case 6. It used 3020 KB of memory. ------ Data for Run 6 ------ 7 ----------------------------

    看了别人的方案,发现好多人使用打表,这个也可以。。。。。。

    不过牛人还是有的,不过这个置换,我没有看懂。

#include <string.h> #include <iostream> #include <fstream> #define maxn 9 using namespace std; ifstream fi("latin.in"); ofstream fo("latin.out"); int n,i,idx; char a[maxn]; bool v[maxn],row[maxn][maxn],col[maxn][maxn]; int cnt[maxn]; unsigned long long total; void calidx() { char i,l,t; idx=2; memset(v,0,sizeof(v)); for (i=1;i<=n;i++) if (!v[i]) { l=0;t=i; do { v[t]=true; t=a[t]; l++; }while (!v[t]); if (l>idx) idx=l; } } void search(char x,char y) { char i; for (i=1;i<=n;i++) if (row[x][i] && col[y][i]) { if (x==2) { a[y]=i; if (y==n) { calidx(); if (cnt[idx]>0) { total+=cnt[idx]; return; } } } row[x][i]=false; col[y][i]=false; if (y==n) { if (x==n-1) { cnt[idx]++; total++; } else search(x+1,2); } else search(x,y+1); row[x][i]=true; col[y][i]=true; } } int main() { fi >> n; if (n==2) total=1; else { memset(row,1,sizeof(row)); memset(col,1,sizeof(col)); memset(cnt,0,sizeof(cnt)); for (i=2;i<n;i++) row[i][i]=false; for (i=1;i<=n;i++) col[i][i]=false; total=0; a[1]=2; search(2,2); for (i=2;i<n;i++) total*=i; } fo << total << endl; fi.close(); fo.close(); return 0; }

你可能感兴趣的:(USACO算法序列四十九——latin)