洛谷 P2119 魔法阵 题解
Analysis
这道题也是考试题,我也依然打了个n三次方暴力。正解是先枚举差,再枚举c和d,a和b用乘法原理优化,这样就能大大减少时间。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #define max_n 50010 6 using namespace std; 7 int n,m,maxn=0,minn=99999999; 8 int a[max_n],book[max_n],ansa[max_n],ansb[max_n],ansc[max_n],ansd[max_n]; 9 inline int read() 10 { 11 int x=0; 12 bool f=1; 13 char c=getchar(); 14 for(; !isdigit(c); c=getchar()) if(c=='-') f=0; 15 for(; isdigit(c); c=getchar()) x=(x<<3)+(x<<1)+c-'0'; 16 if(f) return x; 17 return 0-x; 18 } 19 inline void write(int x) 20 { 21 if(x<0){putchar('-');x=-x;} 22 if(x>9)write(x/10); 23 putchar(x%10+'0'); 24 } 25 int main() 26 { 27 n=read();m=read(); 28 for(int i=1;i<=m;i++) 29 { 30 a[i]=read(); 31 book[a[i]]++; 32 } 33 for(int cha=1;cha*9<n;cha++) 34 { 35 int sum=0; 36 for(int d=9*cha+2;d<=n;d++) 37 { 38 int a=d-9*cha-1; 39 int b=a+2*cha; 40 int c=d-cha; 41 sum+=book[a]*book[b]; 42 ansc[c]+=sum*book[d]; 43 ansd[d]+=sum*book[c]; 44 } 45 sum=0; 46 for(int a=n-9*cha;a>=1;a--) 47 { 48 int b=a+2*cha; 49 int c=b+6*cha+1; 50 int d=c+cha; 51 sum+=book[c]*book[d]; 52 ansa[a]+=sum*book[b]; 53 ansb[b]+=sum*book[a]; 54 } 55 } 56 for(int i=1;i<=m;i++) 57 { 58 printf("%d %d %d %d\n",ansa[a[i]],ansb[a[i]],ansc[a[i]],ansd[a[i]]); 59 } 60 return 0; 61 }
请各位大佬斧正(反正我不认识斧正是什么意思)