2022 RoboCom 世界机器人开发者大赛-本科组(国赛)个人题解

RC-u4 变牛的最快方法

思路

最短编辑距离+记录路径板子题,不懂最短编辑距离的可以看看网上的博客。不懂为什么官方题解用的bfs写法,然后网上所有的题解就是bfs了。我这里就是双重for循环实现,参考下写法即可。

代码

点击查看代码
#include<bits/stdc++.h>
#define x first
#define y second
#define PII pair<int,int>
using namespace std;
const int N = 1e3+9;
int a[N],b[N],n,m,dp[N][N],op[N][N];
PII pre[N][N];
int main() {
	int xx;
	while(cin>>xx&&xx!=-1) a[++n]=xx;
	while(cin>>xx&&xx!=-1) b[++m]=xx;
	memset(op,-1,sizeof op);
	//初始化很重要 
	for(int i=0; i<=n; ++i) dp[i][0]=i,op[i][0]=0,pre[i][0]={i-1,0};//删除 
	for(int i=0; i<=m; ++i) dp[0][i]=i,op[0][i]=3,pre[0][i]={0,i-1};//插入 
	for(int i=1; i<=n; ++i) {
		for(int j=1; j<=m; ++j) {
			int c=(a[i]!=b[j]);
			//如果a[i]==b[j],不一定从dp[i-1][j-1]转移过来就是最优解
			//所以要取最小值 
			int add = dp[i][j-1]+1;//在a[i]前面添加b[j]
			int del = dp[i-1][j]+1;//删除a[i]
			int rce=dp[i-1][j-1]+c;//替换a[i]为b[j]
			dp[i][j]=min(add,min(del,rce));
			if(dp[i][j]==rce) {
				op[i][j]=1;//记录操作 
				pre[i][j]={i-1,j-1};//记录从哪里转移来的,下面同理 
				if(a[i]==b[j]) op[i][j]=2;
			}
			else if(dp[i][j]==add) op[i][j]=3,pre[i][j]={i,j-1};
			else  op[i][j]=0,pre[i][j]={i-1,j};
		}
	}
	cout<<dp[n][m]<<endl;
	//从右下角(n,m)根据pre数组,往回找路径 
	PII t = {n,m};
	vector<int> ans;
	while(t.x||t.y){
		ans.push_back({op[t.x][t.y]});
		t=pre[t.x][t.y]; 
	}
	reverse(ans.begin(), ans.end());
	for(auto &it : ans) cout<<it;
	return 0;
}
/*
in: 
1 -1
3 2 1 -1
out:
2
332 
*/





RC-u5 养老社区

代码

点击查看代码
#include<bits/stdc++.h>
#define ll long long
#define pushk push_back
#define rep(i,x,y) for(int i=x; i<=y; ++i)
using namespace std;
const int N = 2e3+9;
vector<int> g[N];
int dis[N][N],w[N],n;
bitset<N> T[N];
void bfs(int s) {
	queue<int> q;
	rep(i,1,n) dis[s][i]=0x3f3f3f3f;
	q.push(s),dis[s][s]=0;
	while(q.size()) {
		int x = q.front();q.pop();
		for(auto &y: g[x]) {
			if(dis[s][y]>dis[s][x]+1) {
				dis[s][y]=dis[s][x]+1;
				q.push(y);
			}
		}
	}
}
int main() {
	cin>>n;
	for(int i=1; i<n; ++i) {
		int u,v;
		cin>>u>>v;
		g[u].pushk(v),g[v].pushk(u);
	}
	for(int i=1; i<=n; ++i) bfs(i);
	vector<pair<int,int>> D[N];
	rep(i,1,n) {
		rep(j,i+1,n) {
			//cout<<i<<" "<<j<<" "<<dis[i][j]<<endl;
			D[dis[i][j]].pushk({i,j});
		}
	}
	for(int i=1; i<=n; ++i) {
		cin>>w[i];
		T[w[i]].set(i,true);
	}
	ll res=0;
	//枚举距离d
	for(int d=1; d<=n; ++d) {
		bitset<N> se[N];
		for(int i=0; i<D[d].size(); ++i) {
			int a=D[d][i].first,b=D[d][i].second;
			se[a].set(b,true),se[b].set(a,true);
		}
		//	cout<<"de"<<endl;
		for(int i=0; i<D[d].size(); ++i) {
		
			int a=D[d][i].first,b=D[d][i].second;
			if(w[a]!=w[b]){
				//cout<<"de"<<endl;
				res+=(se[a]&se[b]&(~T[w[a]])&(~T[w[b]])).count(); 
			}
		}
	}
	cout<<res/3<<endl;
	return 0;
}
/*
in:
1 -1
3 2 1 -1
out:
2
332
*/


posted @ 2023-06-18 14:49  翔村亲亲鸟  阅读(310)  评论(1编辑  收藏  举报