2018年1月3日 星期三

[C_MM058-中] 二項式求解(C++)

[C_MM058-中] 二項式求解

問題描述 :
給定一二項式,ax+by=c,輸入3個整數,a,b,c,求出所有x,y之非負整數解,並將其解依序列出。
例a=2, b=3, c=10, 2x+3y=10, 解答為x=2,y=2和x=5,y=0;結果列出如下所示:
2,2
5,0


輸入說明 :
輸入a,b,c之值,例如: (照a,b,c順序輸入)
2,3,10
輸出說明 :
輸出x,y解答,例如: (每組解依照x的大小來排序)
2,2
5,0
範例 :

Sample Input:Sample Output:
2,3,102,2
5,0

  1. #include <iostream>  
  2. #include <string>  
  3. #include <sstream>  
  4. #include <algorithm>  
  5. using namespace std;  
  6.   
  7. int main() {  
  8.     // [C_MM058-中] 二項式求解  
  9.     string in;  
  10.     int a, b, c;  
  11.     int count = 0;  
  12.     while(getline(cin, in))  
  13.     {  
  14.         stringstream ss(in);  
  15.         string token;  
  16.         //字串切割  
  17.         while (getline(ss, token, ','))  
  18.         {  
  19.             if(count == 0)  
  20.             {  
  21.                 a = stoi(token);  
  22.                 count++;  
  23.             }  
  24.             else if(count == 1)  
  25.             {  
  26.                 b = stoi(token);  
  27.                 count++;  
  28.             }  
  29.             else if(count == 2)  
  30.             {  
  31.                 c = stoi(token);  
  32.                 count++;  
  33.             }  
  34.         }  
  35.         //ax+by=c  
  36.         for(int i = 0;i < c;i++)  
  37.         {  
  38.             for(int j = 0;j < c;j++)  
  39.             {  
  40.                 if(a*i+b*j == c)  
  41.                 {  
  42.                     cout << i << "," << j << endl;  
  43.                 }  
  44.             }  
  45.         }  
  46.     }  
  47.     return 0;  
  48. }  

沒有留言:

張貼留言