128. [usaco mar08] chaotic Gear
Farmer John recently bought a new machine to help him with the physical work to load hay into the cowshed. However, due to unreasonable design, the machine has many redundant gears. The whole machine is driven by a large gear connected to the motor, which is installed at the position (0, 0 ). FJ wants to know which gear is turned after the machine starts.
FJ records in detail the positions X_ I, y_ I (-1080 <= x_ I <= 5,000) of all N (2 <= n <= 5,000) gears; -5,000 <= y_ I <= 5,000) and radius r_ I (3 <= r_ I <= 1024 ). Your task is to find the position of the gear at the end of the entire drive system (a gear driven by another gear but not driven by any other gear. In addition to the main gear that drives the entire machine, other gears will only be driven by another gear.
Program name: Rollers
Input Format:
- Line 2nd. n + 1: line I + 1 gives the parameters of gear I: X_ I, y_ I, and r_ I.
Input example (rollers. In ):
30 0 3030 40 20-15 100 55
Input description:
There are three gears in the machine. The first gear is placed at the origin with a radius of 30. It drives the gear with a radius of 20 (30, 40), so the gear with a radius of 55 (-15,100) is eventually driven by the second gear.
Output Format:
- Row 3: Output two integers x and y separated by spaces, indicating the position of the end gear of the drive system.
Output example (rollers. out ):
-15 100
Create a Graph Based on the question. Then BFs.
#include<cstdio>#include<queue>using namespace std;const int maxn = 1100;int x[maxn],y[maxn],r[maxn];int f[maxn][maxn];bool vis[maxn];int dist(int x1,int y1,int x2,int y2){ return (x1-x2)*(x1-x2)+(y1-y2)*(y1-y2);}int s,ans,n;void bfs(){ queue<int > q; q.push(s); vis[s]=true; while(!q.empty()){ int now = q.front();q.pop(); for(int i=1;i<=n;i++){ if(!vis[i]&&f[now][i]){ vis[i]=true; ans=i; q.push(i); } } }}int main(){ freopen("rollers.in","r",stdin); freopen("rollers.out","w",stdout); scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d%d%d",&x[i],&y[i],&r[i]); if(x[i]==0&&y[i]==0){ s=i; } } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(i!=j){ int s=dist(x[i],y[i],x[j],y[j]); if(s<=(r[i]+r[j])*(r[i]+r[j])){ f[i][j]=1; } } } } bfs(); printf("%d %d\n",x[ans],y[ans]); return 0;}