AtCoder Beginner Contest 197 F - Construct a Palindrome

https://atcoder.jp/contests/abc197/tasks/abc197_f

I won't know the routine of a car. . .

Convert the topic into a two-dimensional plane model, dis[u][v] means the distance from 1 to u, from n to v, the same letter

Then we enumerate all the edges of each point u:{s,e}, get u:{s,e}->v:{sv,ev} such edges, and they go the same letter, so enumerate Max m^2

Then bfs is fine, and then enumerate the middle dis[i][i]*2 and dis[i][j]*2+1, i,j, there are edges in the middle, and the answer is the smallest solution.

Note that the answer cannot be directly taken as dis[1][n]->dis[n][1]

4 4

1 2 b

2 4 a

1 3 a

3 4 b

So going from (1,n) to (n,1) is a ring, but not a palindrome

 

#include<bits/stdc++.h>
using namespace std;

const int maxl=1010;

int n,m,ans;
int dis[maxl][maxl];
struct ed{int v,l;}; 
vector<ed> e[maxl];
struct node{int s,e;};
vector<node> g[maxl][maxl];
char s[10];
bool vis[maxl][maxl];

inline void prework()
{
	scanf("%d%d",&n,&m);
	for(int i=1;i<=m;i++)
	{
		int u,v;
		scanf("%d%d",&u,&v);vis[u][v]=vis[v][u]=true;
		scanf("%s",s);
		e[u].push_back(ed{v,s[0]-'0'});
		e[v].push_back(ed{u,s[0]-'0'});
	}
	for(int i=1;i<=n;i++)
		for(int j=1;j<=n;j++)
			for(ed e1:e[i])
				for(ed e2:e[j])
				if(e1.l==e2.l)
					g[i][j].push_back(node{e1.v,e2.v});
}

inline void mainwork()
{
	memset(dis,0x3f,sizeof(dis));
	dis[1][n]=0;int inf=dis[0][0];
	queue<node> q;q.push(node{1,n});
	while(!q.empty())
	{
		node u=q.front();q.pop();
		for(node v:g[u.s][u.e])
		if(dis[v.s][v.e]==inf)
		{
			dis[v.s][v.e]=dis[u.s][u.e]+1;
			q.push(node{v.s,v.e});
		}
	}
	ans=inf;
	for(int i=1;i<=n;i++)
	{
		ans=min(ans,dis[i][i]*2);
		for(int j=1;j<=n;j++)
		if(vis[i][j])
			ans=min(ans,dis[i][j]*2+1);
	}
}

inline void print()
{
	if(ans==dis[0][0])
		ans=-1;
	printf("%d",ans);
}

int main()
{
	prework();
	mainwork();
	print();
	return 0;
}

 

Guess you like

Origin blog.csdn.net/liufengwei1/article/details/115361184