题目:Gear-wheels
题意:读入N ((1 ≤ N ≤ 1000) 表示有N个齿轮,随后N行,每一行读入Ki, 表示第N个齿轮的数目,随后读入若干个数(0结束),表示第 i 个齿轮与其相接。最后一行读入M、V,表示第M个齿轮与发动机相连通,发动机转速为V,求所有齿轮的速度。
解法:直接暴力地从M开始搜索,通过M来计算其他齿轮的转速,注意如果是0,要输出“0/1”
#include <iostream>
using namespace std;
const int maxn = 1010;
int map[maxn][maxn] = {0}, a[maxn], ans[maxn][3], n, d[maxn];
bool f[maxn];
int gdb(int x, int y) {
while (y != 0) {
int temp = y;
y = x%y;
x = temp;
}
return x;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
f[i] = true;
cin >> a[i];
int x;
cin >> x;
while (x != 0) {
map[i][x] = 1;
cin >> x;
}
ans[i][2] = 1;
}
int m;
cin >> m;
f[m] = false;
cin >> ans[m][1];
ans[m][2] = 1;
ans[m][0] = 1;
d[1] = m;
int l = 0, r = 1;
while (l < r) {
l++;
int x = d[l];
for (int i = 1; i <= n; i++) if (map[x][i] && f[i]) {
f[i] = false;
d[++r] = i;
ans[i][0] = ans[x][0]*-1;
ans[i][1] = ans[x][1]*a[x];
ans[i][2] = ans[x][2]*a[i];
int t = gdb(ans[i][1], ans[i][2]);
ans[i][1] /= t;
ans[i][2] /= t;
}
}
for (int i = 1; i <= n; i++) {
cout << ans[i][0]*ans[i][1] << "/" << ans[i][2] << endl;
}
}