题目
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6853
题目大意:从x,y开始游走,每次只能走gcd(x,y)>1的点或者是留在原来的点,求从s开始游走,最后再回到点s的概率
思路
这道题要用到一个结论:
即对于任意一张无向图,从 s 开始随机游走回到 s 的概率为 (s 的度数+1)/(+1)/(整张图的总度数+n)+n)。
所以我们只用bfs求出整张连通图,算出s的度数与整张图的总度数即可
代码
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<cctype>
#include<ctime>
#include<iostream>
#include<string>
#include<map>
#include<queue>
#include<stack>
#include<set>
#include<vector>
#include<iomanip>
#include<list>
#include<bitset>
#include<sstream>
#include<fstream>
#include<complex>
#include<algorithm>
#if __cplusplus >= 201103L
#include <unordered_map>
#include <unordered_set>
#endif
#define int long long
using namespace std;
const int INF = 0x3f3f3f3f;
int dir[10][2]={1,0,-1,0,0,1,0,-1,1,1,1,-1,-1,-1,-1,1};
struct sut{
int x,y;
};
void bfs(int x,int y){
queue<sut> q;
set<pair<int,int>> st;
int res1=0,res2=0;
q.push(sut{x,y});
st.emplace(x,y);
while(!q.empty()){
sut now = q.front();
q.pop();
// cout<<now.x<<" "<<now.y<<endl;
if(now.x==now.y){
res1=0,res2=1;
break;
}
res2++;//注意这里要算上自己
for(int i=0;i<8;i++){
int dx=now.x+dir[i][0];
int dy=now.y+dir[i][1];
//cout<<dx<<" "<<dy<<endl;
if(__gcd(dx,dy)==1) continue;
res2++;
if(st.count(make_pair(dx,dy))) continue;
st.emplace(dx,dy);
q.push(sut{dx,dy});
}
if(res1==0) res1=res2;
//cout<<res1<<" "<<res2<<endl;
}
int gcd=__gcd(res1,res2);
cout<<res1/gcd<<"/"<<res2/gcd<<endl;
}
signed main(){
ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
int t;
cin>>t;
while(t--){
int x,y;
cin>>x>>y;
bfs(x,y);
}
return 0;
}