Poj--2947(数学,高斯消元,模线性方程)
2014-09-18 22:44:04
思路:比较裸的高斯消元+同余方程。注意几点:(1)对所有输入模7!Gauss过程中也要模7 (2)多解是由自由变元个数决定。
1 /************************************************************************* 2 > File Name: 2947.cpp 3 > Author: Nature 4 > Mail: 564374850@qq.com 5 > Created Time: Thu 18 Sep 2014 08:34:31 PM CST 6 ************************************************************************/ 7 8 #include <cstdio> 9 #include <cstring> 10 #include <cstdlib> 11 #include <cmath> 12 #include <vector> 13 #include <queue> 14 #include <map> 15 #include <iostream> 16 #include <algorithm> 17 using namespace std; 18 typedef long long ll; 19 const int INF = 1 << 29; 20 21 inline int Gcd(int a,int b){ return b == 0 ? a : Gcd(b,a % b); } 22 inline int Lcm(int a,int b){ return a / Gcd(a,b) * b; } 23 24 int n,m; 25 int A[305][305]; 26 27 int Check(char *s){ 28 if(strcmp(s,"MON") == 0) return 1; 29 if(strcmp(s,"TUE") == 0) return 2; 30 if(strcmp(s,"WED") == 0) return 3; 31 if(strcmp(s,"THU") == 0) return 4; 32 if(strcmp(s,"FRI") == 0) return 5; 33 if(strcmp(s,"SAT") == 0) return 6; 34 if(strcmp(s,"SUN") == 0) return 7; 35 } 36 37 int Gauss(){ 38 int equ,var; equ = m; var = n; 39 int i,j,k,r,col,LCM,ta,tb; 40 col = 0; 41 for(i = 0; i < equ && col < var; ++i,++col){ 42 r = i; 43 for(j = i + 1; j < equ; ++j) 44 if(abs(A[j][col]) > abs(A[r][col])) r = j; 45 if(r != i) 46 for(j = col; j <= var; ++j) swap(A[i][j],A[r][j]); 47 if(A[i][col] == 0){ 48 --i; 49 continue; 50 } 51 for(k = i + 1; k < equ; ++k) if(A[k][col]){ 52 LCM = Lcm(abs(A[i][col]),abs(A[k][col])); 53 ta = LCM / abs(A[i][col]); 54 tb = LCM / abs(A[k][col]); 55 if(A[i][col] * A[k][col] < 0) ta = -ta; 56 for(j = col; j <= var; ++j) 57 A[k][j] = ((A[k][j] * tb - A[i][j] * ta) % 7+ 7) % 7; 58 } 59 } 60 for(k = i; k < equ; ++k) if(A[k][col] != 0) 61 return -2; 62 if(var - i > 0) 63 return -1; 64 for(i = var - 1; i >= 0; --i){ 65 for(j = i + 1; j < var; ++j){ 66 A[i][var] = ((A[i][var] - A[i][j] * A[j][var]) % 7 + 7) % 7; 67 } 68 while(A[i][var] % A[i][i] != 0) A[i][var] += 7; 69 A[i][var] /= A[i][i]; 70 while(A[i][var] < 3) A[i][var] += 7; 71 while(A[i][var] > 9) A[i][var] -=7; 72 } 73 return 1; 74 } 75 76 77 78 int main(){ 79 int num,a; 80 char st[10],ed[10]; 81 while(scanf("%d%d",&n,&m) != EOF){ 82 if(n == 0 && m == 0) 83 break; 84 memset(A,0,sizeof(A)); 85 for(int i = 0; i < m; ++i){ 86 scanf("%d%s%s",&num,st,ed); 87 while(num--){ 88 scanf("%d",&a); 89 A[i][a - 1]++; 90 A[i][a - 1] %= 7; 91 } 92 A[i][n] = (Check(ed) - Check(st) + 1 + 7) % 7; 93 } 94 int t = Gauss(); 95 if(t == -2) printf("Inconsistent data.\n"); 96 else if(t == -1) printf("Multiple solutions.\n"); 97 else{ 98 printf("%d",A[0][n]); 99 for(int i = 1; i < n; ++i) printf(" %d",A[i][n]); 100 puts(""); 101 } 102 } 103 return 0; 104 }

浙公网安备 33010602011771号