我是靠谱客的博主 自觉金针菇,最近开发中收集的这篇文章主要介绍UVa331 - Mapping the Swaps,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

题目地址:点击打开链接

就是BFS,对每一个前一个元素大于后一个元素的位置,交换这两个元素,压入队列。最后如果碰到队列中已经有排好序的元素,统计所有排好序的个数就可以了。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> sorted_array;
const int maxsize = 1000000;
vector<int> que[maxsize];
vector<int> vi;
int n;
int front,rear,last;
int num;
bool check()
{
	bool flag=false;
	for(int i=0;i<n-1;++i)
	{
		if(que[front][i]>que[front][i+1])
		{
			flag=true;
			vector<int> v(que[front]);
			int temp=v[i];
			v[i]=v[i+1];
			v[i+1]=temp;
			que[rear++]=v;
		}
	}
	return flag;
}
void count()
{
	num=0;
	while(front!=last)
	{
		if(!check())
			++num;
		++front;
	}
	if(vi==sorted_array)
		num=0;
}
void bfs()
{
	front=0;rear=1;last=1;
	que[front]=vi;
	while(front!=rear)
	{
		while(front!=last)
		{
			if(check())
				++front;
			else
			{
				count();
				return;
			}
		}
		last=rear;
	}
}
int main()
{
	int cas=1;
	while(cin>>n&&n!=0)
	{
		sorted_array.clear();
		vi.clear();
		for(int i=0;i<n;++i)
		{
			int x;
			cin>>x;
			sorted_array.push_back(x);
			vi.push_back(x);
		}
		sort(sorted_array.begin(),sorted_array.end());
		bfs();
		cout<<"There are "<<num<<" swap maps for input data set "<<cas++<<"."<<endl;
	}
	return 0;
}


最后

以上就是自觉金针菇为你收集整理的UVa331 - Mapping the Swaps的全部内容,希望文章能够帮你解决UVa331 - Mapping the Swaps所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(65)

评论列表共有 0 条评论

立即
投稿
返回
顶部