2016-03-10 44 views
-1
#include <iostream> 
#include <set> 
#include <algorithm> 
using namespace std; 

int cost[10][10]; 
string team[10]; 
int perm[10]; 

int main() { 

    int R; 
    cin >> R; 
    for (int j=0; j<R; j++) { 
     cin >> team[j]; 
     perm[j] = j; 
    } 

    for (int a=0; a < R; a++) 
     for (int b=0; b < a; b++) { 
      string combined = team[a]+team[b]; 
      int overlap = combined.size() - set<char>(combined.begin(), combined.end()).size(); 
      cost[a][b] = cost[b][a] = overlap; 
     } 

    int best = 27*R; 
    do { 
     int count=0; 
     for (int j=0; j < R-1; j++) 
      count += cost[perm[j]][perm[j+1]]; 
     best = min(best,count); 
    } while (next_permutation(perm,perm+R)); 

    cout << best << endl; 
} 

上面的代碼是C++,我不知道如何代碼的這部分翻譯:int overlap = combined.size() - set<char>(combined.begin(), combined.end()).size();如何將這一小部分C++代碼轉換爲C?

這是我到目前爲止有:

#include <string.h> 
#include <stdlib.h> 
#include <stdio.h> 

int cost[10][10]; 
char team[10]; 
int perm[10]; 

int main() { 

    int R,j; 
    scanf("%d", R); 

    for (j=0; j<R; j++) { 
     scanf("%d", team[j]); 
     perm[j] = j; 
    } 

    // calculate all-pairs costs 
    int a , b; 
    for (a=0; a < R; a++) 
     for (b=0; b < a; b++) { 
      strcat(team[a], team[b]); 
      int overlap = combined.size() - set<char>(combined.begin(), combined.end()).size(); 
      cost[a][b] = cost[b][a] = overlap; 
     } 

    // determine best permutation 
    int best = 27*R; 
    do { 
     int count=0; 
     for (int j=0; j < R-1; j++) 
      count += cost[perm[j]][perm[j+1]]; 
     best = min(best,count); 
    } while (next_permutation(perm,perm+R)); 

    printf("%d\n", best); 
} 

如果你們能指出我的其他錯誤在哪裏,或者如果有人能幫我翻譯,我會很感激。

+0

您的編譯器會爲您指出一些錯誤。 –

回答

0

你翻譯stringchar,這是不正確,一個快速的一個骯髒的解決方案,你可以定義team這樣:

char team[10][100]; 

但是,一個更加堅固的解決方案,您將定義char *team[10]並分配和重新分配讀取字符串並連接它們。您可能還需要翻譯set<char>(combined.begin(), combined.end()).size()

+0

我將如何翻譯集合(combined.begin(),combined.end())。size()? – HiWorld567

+0

'combined'應該是一個單獨的數組,在其中計算字符串'team [a]'和'team [b]'的聯合,您當前的方法在您修改team [a]時不起作用。如果你不明白它的作用,那麼很難翻譯一個程序。 – chqrlie

0

scanf(format, ...)需要指向變量的指針,以便函數知道在哪裏存儲輸入。例如)

scanf("%d", &R);