Purple Book Exercise 8-7 UVa 11925 (Construction method, no reverse required)

The meaning of this question is wrong on the purple book...

No wonder at first I was very curious why the output of the second sample is 2, according to the meaning of the purple book, it should be 22

Then don't care, write first, then WA.

Then I read https://blog.csdn.net/wcr1996/article/details/43774331

It was found that the meaning of the title was wrong.

is the permutation from 1 to n to the permutation given, not the other way around

Other people's blogs are written with reverse thinking, which is the way I wrote by mistake, but the operation is reversed, and finally

The output is reversed. This method is worth learning

In fact, it is not difficult to be positive, it is nothing more than setting a new priority


Treat the original arrangement of 1 to n as out of order, and regard the given arrangement as ordered, just assign an id to each value.

Then I was surprised to find that the answer to write the final output directly is exactly the same as the output sample given.

It may be that the person who asked the question was writing it in the right direction.

My idea of ​​solving the problem is to "ignore" the exchange needs to be held at the beginning at the beginning, search it first and then when the search is not in ascending order, just exchange these two elements directly

Put it in the head when exchanging. In fact, it is to swap the sequences that are not in ascending order, and then keep doing this until they are all in ascending order.

However needing to do it at the head is just a "by-product". See the code for details.



#include<cstdio>
#include<vector>
#include<algorithm>
#include<queue>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;

const int MAXN = 312;
int id[MAXN], n;
deque<int> q;
vector<int> ans;

void Swap(int cur)
{
	REP(i, 0, cur)
	{
		q.push_back(q.front());
		q.pop_front();
		ans.push_back(2);
	}
	ans.push_back(1);
	swap(q[0], q[1]);
}

bool check()
{
	REP(i, 0, n)
	{
		if(id[q[i]] > id[q[(i+1)%n]] && !(id[q[i]] == n && id[q[(i+1)%n]] == 1))
		{
			Swap(i);
			return true;
		}
	}
	return false;
}

intmain()
{
	while(~scanf("%d", &n) && n)
	{
		ans.clear();
		while(!q.empty()) q.pop_back();
		
		int start, x;
		REP(i, 1, n + 1)
		{
			scanf("%d", &x);
			id[x] = i;
			q.push_back(i);
		}
		
		while(check());
		if(id[q[0]] != 1)
		{
			for(start = 0; id[q[start]] != 1; start++);
			REP(i, 0, start) ans.push_back(2);
		}
		REP(i, 0, ans.size()) printf("%d", ans[i]);
		puts("");
	}
	
	return 0;
}


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325949857&siteId=291194637