sicily 6415. linear correlation

Description

向量u=(a1, a2, ...., an)和向量v=(b1, b2, ....., bn)为Rn中的两个向量,判断它们是否线性相关。

Input

输入包括多组测试用例,每组测试用例包括三行。

第一行是一个数n(2<=n<=10),表示向量的维数。

第二行是向量u的n个元素。

第三行是向量v的n个元素。

当输入的n为0时结束。

Output

 对于每组测试用例输出一行。

如果u和v线性相关,则输出Yes,否则输出No。

这道题的测试用例似乎很糟糕,一开始写了N个漏洞多多的程序居然都给AC(包括判定一个含零向量的向量组线性无关,判定一个每项都是另一向量不同倍的向量为线性相关,某一项有零就判断出错之类的漏洞程序),还需要自己在检查过程中不断修改,最后成品是这个样子,就自己设计测试的用例(包括零向量,含零非零向量,小数,负数)来说暂时没发现有什么大问题

懒得再写一遍题解了,直接存一下提交作业时写的英文函数注释

/*
 * algorithm:
 *  1. create an array to store each scaler that transform each entry of v into
 *     corresponding entry of u. if one or two of the entires is 0, then the 
 *     scaler would be stored as 0;
 *  2. bubble sort the array of scalers;
 *  3. if the smallest nonzero scaler equals to the greatst one, then this 
 *     nonzero scaler could transform the entire v into u, thus u and v are
 *     linearly correlated. otherwise they are not linearly correlated.
 */
View Code
 1 #include<stdio.h>
 2 #include<math.h>
 3 
 4 int correlation( double u[], int sizeu, double v[], int sizev );
 5 void bubbleSort ( double array[], int size );
 6 
 7 int main()
 8 {
 9     int n, i = 0, j = 0;
10     double u[10];
11     double v[10];
12     
13     while ( scanf("%d", &n ) && ( n != 0 ) )
14     {
15         for ( i = 0; i < n; i++ )
16         {
17             scanf("%lf", &u[i]); 
18         }
19         
20         for ( i = 0; i < n; i++ )
21         {
22             scanf("%lf", &v[i]);
23         }
24         
25         if ( correlation(u, n, v, n) == 1 )
26         {
27             printf( "%s\n", "Yes" );
28         }
29         else
30         {
31             printf( "%s\n", "No" );
32         } 
33     }
34     
35     return 0;
36 }
37  
38 int correlation( double u[], int sizeu, double v[], int sizev )
39 {
40     int i;
41     int n = sizeu;
42     double scaler[n];
43     
44     for ( i = 0; i < n; i++ )
45     {
46         if ( fabs( u[i] ) < 0.000001 || fabs( v[i] ) < 0.000001 )
47         {
48             scaler[i] = 0.0;
49         }
50         else
51         {
52             scaler[i] = u[i] / v[i];
53         }
54     }
55     
56     bubbleSort( scaler, n );
57     
58     i = 0;
59     while ( fabs(scaler[i]) < 0.000001 && i < n )
60     {
61         i++;
62     }
63     
64     if ( fabs( scaler[n-1] - scaler[i] ) < 0.000001 )
65     {
66         return 1;
67     }
68     else
69     {
70         return 0;
71     }
72 }
73 
74  
75 void bubbleSort ( double array[], int size )
76 {
77     int i, j;
78     double temp;
79     
80     for ( i = 0; i < size; i++ )
81     {
82         for( j = 0; j < size - 1 - i; j++ )
83         {
84             if ( array[j] > array[j+1] )
85             {
86                 temp = array[j];
87                 array[j] = array[j+1];
88                 array[j+1] = temp;
89             }
90         }
91     }
92 }
原文地址:https://www.cnblogs.com/joyeecheung/p/2776459.html