这题过的人很少,却意外的很水呢
#include <iostream>
#include <string>
#include <map>
using namespace std;
char ch;
int k1,k2,a[201][201][2],tot,g;
string s,ss;
map<string,int> ma;
int gcd(int a,int b) {
if (b==0) return a;
else return gcd(b,a%b);
}
int main() {
tot = 0;
ma.clear();
while (scanf("%c",&ch)) {
if (ch=='.') break;
else if (ch=='!') {
scanf("%d",&k1);
cin >> s;
if (ma[s]==0) ma[s] = ++tot;
scanf(" = %d",&k2);
cin >> ss;
if (ma[ss]==0) ma[ss] = ++tot;
a[ma[s]][ma[ss]][0] = k1;
a[ma[s]][ma[ss]][1] = k2;
a[ma[ss]][ma[s]][0] = k2;
a[ma[ss]][ma[s]][1] = k1;
for (int k=1;k<=tot;k++)
for (int i=1;i<=tot;i++)
for (int j=1;j<=tot;j++)
if (i==j) continue;
else if (a[i][j][0]==0 && a[i][k][0]!=0 && a[k][j][0]!=0) {
a[i][j][0] = a[i][k][0]*a[k][j][0];
a[i][j][1] = a[i][k][1]*a[k][j][1];
}
}
else {
cin >> s;
scanf(" = ");
cin >> ss;
k1 = ma[s];
k2 = ma[ss];
if (a[k1][k2][0]==0) cout << "? " << s << " = ? " << ss << endl;
else {
g = gcd(a[k1][k2][0],a[k1][k2][1]);
cout << a[k1][k2][0]/g << ' ' << s << " = " << a[k1][k2][1]/g << ' ' << ss << endl;
}
}
getchar();
}
return 0;
}