Atcoder Beginner Contest 244 F

F - Shortest Good Path

Title:

Give you n points, m edges, no double edges, no self-loops

If a sequence is satisfied, all are in 1-N and there is an edge connection between the two points.

There is also 1 0 indicating whether the number of times the path passes through point i is odd or even

answer:

1. How to express it?

(1) Use a vector to represent the input, and then use auto to get the corresponding value.

(2) dis[i][j] indicates that the current state is i "represented in binary" and the number is j.

2. How to do it?

(1) Why do you want u-1, v-1 in the first place? Because you want to use binary operations, such as 0001, it is (1<<0) instead of (1<<1)

(2) BFS, start from a number and search backwards, if you haven't searched, continue to search, then +1, if you have searched, then don't

//
#include <iostream>
#include <vector>
#include <queue>
#define int long long
using namespace std;
const int N = (1 << 17);
const int INF = 0x3f3f3f3f3f3f3f3f;
int dis[N][17];
vector<int> G[20];
queue<pair<int, int>> Q;
int n,m;
signed main() {
	cin>>n>>m;
	for(int i=1;i<=m;i++){
		int u,v;
		cin>>u>>v;
		u--,v--;
		G[u].push_back(v);
		G[v].push_back(u);
	}
	int M = 1<<n;
	for(int i=0;i<M;i++)
		for(int j=0;j<n;j++)
			dis[i][j]=INF;
//		这里为啥要一开始初始化为1呢?
//		因为我一个数,length为1!
	for(int i=0;i<n;i++){
		dis[1<<i][i]=1;
		Q.push({1<<i,i});
	}
	//		BFS
	while(Q.size()){
		int s = Q.front().first;
		int v = Q.front().second;
		Q.pop();
		for(auto u : G[v]){
			int ns = s ^ (1<<u);
			if(dis[ns][u]<INF) continue;
			dis[ns][u] = dis[s][v] + 1;
//			这就是挑出来的那一个
			Q.push({ns,u});
		}
	}
	int ans = 0;
//	最后是对所有情况进行加总
	for(int i=1;i<M;i++){
		int mm = INF;
		for(int j=0;j<n;j++){
			mm = min(mm,dis[i][j]);
		}
		ans += mm;
	}
	cout<<ans<<endl;
}

Guess you like

Origin blog.csdn.net/weixin_60789461/article/details/123651453