最小乘積(基本型)

來源:互聯網
上載者:User

標籤:clu   排序   bsp   nbsp   順序   表示   圖片   序號   style   

問題描述  給兩組數,各n個。
  請調整每組數的排列順序,使得兩組資料相同下標元素對應相乘,然後相加的和最小。要求程式輸出這個最小值。
  例如兩組數分別為:1 3 -5和-2 4 1
  那麼對應乘積取和的最小值應為:
  (-5) * 4 + 3 * (-2) + 1 * 1 = -25 輸入格式  第一個行一個數T表示資料群組數。後面每組資料,先讀入一個n,接下來兩行每行n個數,每個數的絕對值小於等於1000。
  n<=8,T<=1000輸出格式  一個數表示答案。範例輸入
231 3 -5-2 4 151 2 3 4 51 0 1 0 1
範例輸出
-256
思路
  沒什麼太多問題,一個簡單排序,用數組A的最小值乘以數組B的最大值即可,翻轉一下也是可以的。

 1 #include<iostream> 2 #include<algorithm> 3  4 using namespace std; 5  6 int main() 7 { 8     int n = 0, m = 0; 9     int s = 0;10     cin>>n;11     // 儲存結果 12     int *sum = new int[n]();13     while(s!=n){14         cin>>m;15         int *a = new int[m]();16         int *b = new int[m]();17         for(int i=0;i<m;i++){18             cin>>a[i];19         }20         for(int i=0;i<m;i++){21             cin>>b[i];22         }23         // 排序很重要 24         sort(a, a+m);25         sort(b, b+m);26         // 相乘時注意序號 27         for(int i=0, j=m-1;i<m;i++,j--){28             sum[s] += (a[i] * b[j]);29         }30         s++;31         delete []a;32         delete []b;33     }34     for(int i=0;i<n;i++){35         cout<<sum[i]<<endl;36     }37     38     delete []sum;39     40     system("pause");41     return 0;42 }
View Code

22:20:49


 

最小乘積(基本型)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.