ACM-ICPC 2017 南宁赛区网络预赛 J Minimum Distance in a Star Graph 【模拟+索引】

  •  1000ms
  •  262144K

In this problem, we will define a graph called star graph, and the question is to find the minimum distance between two given nodes in the star graph.

Given an integer nn, an n-dimensionaln−dimensional star graph, also referred to as Sn​, is an undirected graph consisting of n! nodes (or vertices) and ((n−1) ∗ n!)/2 edges. Each node is uniquely assigned a label x1​ x2​ ... xn​which is any permutation of the n digits1,2,3,...,n. For instance, an S4​ has the following 24 nodes 1234,1243,1324,1342,1423,1432,2134,2143,2314,2341,2413,2431,3124,3142,3214,3241,3412,3421,4123,4132,4213,4231,4312,4321. For each node with label x1​ x2​x3​ x4​ ... xn​, it has n-1n−1 edges connecting to nodes x2​ x1​ x3​ x4​ ... xn​,x3​ x2​ x1​ x4​ ... xn​,x4​ x2​ x3​ x1​ ... xn​, ..., and xn​ x2​ x3​ x4​ ... x1​. That is, the n−1 adjacent nodes are obtained by swapping the first symbol and the d-thd−th symbol of x1​ x2​ x3​ x4​ ... xn​, for d=2,...,n. For instance, in S4​, node 1234 has 3 edges connecting to nodes 2134, 3214, and 4231. The following figure shows how S4​ looks (note that the symbols a, b, c, and d are not nodes; we only use them to show the connectivity between nodes; this is for the clarity of the figure).

image

In this problem, you are given the following inputs:

  • nn: the dimension of the star graph. We assume that nn ranges from 44 to 99.
  • Two nodes x1​ x2​ x3​ ... xn​ and y1​ y2​ y3​ ... yn​ in Sn​.

You have to calculate the distance between these two nodes (which is an integer).

Input Format

nn (dimension of the star graph)

A list of 5 pairs of nodes.

Output Format

A list of 5 values, each representing the distance of a pair of nodes.

样例输入

4
1234 4231
1234 3124
2341 1324
3214 4213
3214 2143

样例输出

1
2
2
1
3

题目来源

2017 ACM-ICPC 亚洲区(南宁赛区)网络赛

题目大意:123...n的一个全排列作为一个结点的标识,一个结点可以通过长度为1的路径到达下一个结点,下一个结点是指此结点的标识的第一个数和后面任意一个数交换后的全排列,给你5组结点,每组2个结点,问从一个结点到另一个结点的最短路径

题解:用字符串标识结点,s1保持不变,将s2变为s1,由于只能将第一个数和后面的数交换,因此 需要这样考虑:
1.当s2[0]不等于s1[0]时,将s2[0]换到正确的位置 
2.当s2[0]等于s1[0]时,如果还不匹配,就将s2后面第一个不匹配的数和s2[0]交换 

AC的C++代码:

#include<iostream>
#include<string>

using namespace std;

int n;
bool fail(string s1,string s2)
{
	for(int i=0;i<n;i++)
	  if(s1[i]!=s2[i])
	    return true;
	return false;
}

int main()
{
	int right[13]; 
	string s1,s2;
	cin>>n;
	for(int i=1;i<=5;i++){
		cin>>s1>>s2;
		for(int j=0;j<n;j++)
		  right[s1[j]-'0']=j;
        int ans=0;
		while(fail(s1,s2)){//如果不匹配就持续操作 
			if(s2[0]!=s1[0]){
				ans++;
				int k=right[s2[0]-'0'];//k为s2[0]应在的位置 
				swap(s2[0],s2[k]);
			}
			else{
				//找到第一个不匹配的位置j
				ans++;
				int j; 
				for(j=1;j<n&&j==right[s2[j]-'0'];j++);
				swap(s2[0],s2[j]);
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/SongBai1997/article/details/82260100