例题1 uva 11538 http://acm.hust.edu.cn/vjudge/problem/28978
在m*n棋盘上放置 黑白两个皇后,相互攻击的方法数.
解法,正着考虑, 同行,同列, 斜着的情况加在一起, 组合书计算一下, 黑白不同 所以是 P(n,2).
对斜着的角的情况暴力算也过. 1760ms
1 //#define txtout 2 //#define debug 3 #include<bits/stdc++.h> 4 #define mt(a,b) memset(a,b,sizeof(a)) 5 using namespace std; 6 typedef long long LL; 7 const double pi=acos(-1.0); 8 const double eps=1e-8; 9 const int inf=0x3f3f3f3f; 10 const int M=1e5+10; 11 int n,m; 12 LL getRow(int r,int c){ 13 return 1LL*c*(c-1)*r; 14 } 15 LL getFirst(int r){ 16 LL sum=0; 17 for(int i=2;i<=r;i++){ 18 sum+=1LL*i*(i-1); 19 } 20 return sum; 21 } 22 LL get(int r,int c){ 23 int small=min(r,c); 24 int sub=max(r,c)-small+1; 25 return getRow(sub,small)+2*getFirst(small-1); 26 } 27 LL solve(){ 28 return getRow(n,m)+getRow(m,n)+get(n,m)+get(m,n); 29 } 30 int main(){ 31 #ifdef txtout 32 freopen("in.txt","r",stdin); 33 freopen("out.txt","w",stdout); 34 #endif // txtout 35 while(~scanf("%d%d",&n,&m),n|m){ 36 printf("%lld\n",solve()); 37 } 38 return 0; 39 }
对斜着的角的预处理, 快非常多. 0ms
1 //#define txtout 2 //#define debug 3 #include<bits/stdc++.h> 4 #define mt(a,b) memset(a,b,sizeof(a)) 5 using namespace std; 6 typedef long long LL; 7 const double pi=acos(-1.0); 8 const double eps=1e-8; 9 const int inf=0x3f3f3f3f; 10 const int M=1e6+10; 11 int n,m; 12 LL sum[M]; 13 void init(){ 14 sum[0]=0; 15 sum[1]=0; 16 for(int i=2;i<M;i++){ 17 sum[i]=sum[i-1]+1LL*i*(i-1); 18 } 19 } 20 LL getRow(int r,int c){ 21 return 1LL*c*(c-1)*r; 22 } 23 LL getFirst(int r){ 24 return sum[r]; 25 } 26 LL get(int r,int c){ 27 int small=min(r,c); 28 int sub=max(r,c)-small+1; 29 return getRow(sub,small)+2*getFirst(small-1); 30 } 31 LL solve(){ 32 return getRow(n,m)+getRow(m,n)+get(n,m)+get(m,n); 33 } 34 int main(){ 35 #ifdef txtout 36 freopen("in.txt","r",stdin); 37 freopen("out.txt","w",stdout); 38 #endif // txtout 39 init(); 40 while(~scanf("%d%d",&n,&m),n|m){ 41 printf("%lld\n",solve()); 42 } 43 return 0; 44 }
end
时间: 2024-10-12 04:31:40