Limited Insertion

本文探讨了Snuke在序列操作上的问题,通过逆向思维解决了一个有趣的数学谜题。给定一个序列,判断其是否能通过特定的插入操作得到,并提供一种可能的操作序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Limited Insertion

题目描述:
Snuke has an empty sequence a.
He will perform N operations on this sequence.
In the i-th operation, he chooses an integer j satisfying 1≤j≤i, and insert j at position j in a (the beginning is position 1).
You are given a sequence b of length N. Determine if it is possible that a is equal to
b after N operations. If it is, show one possible sequence of operations that achieves it.
Constraints
·All values in input are integers.
·1≤N≤100
·1≤bi≤N
输入:
Input is given from Standard Input in the following format:
N
b1 … bN
输出:
If there is no sequence of N operations after which a would be equal to b, print -1. If there is, print N lines. In the i-th line, the integer chosen in the i-th operation should be printed. If there are multiple solutions, any of them is accepted.
样例输入:
3
1 2 1
样例输出:
1
2
题目大意:Snuke有一个空序列a。他将对这个序列执行N个操作。在第i次操作中,他选择一个满足1≤j≤i的整数j,将j插入a的位置j(起始位置为1)。给定一个长度为n的序列b,判断a是否可能等于b经过N次运算。如果是,显示一个可能实现它的操作序列,如果不是,输出-1。
思路:从后往前搜,找到第一个i和a[i]对应的数就放入另一个数组里(不能从前往后搜,比如 1,2,3,放入新数组的顺序应该是3,2,1,最后倒序输出),并将其后面的数往前移一位;重新从后往前搜……重复此过程,中间以k记录,若退出循环是k==n,则是可以的,否则不可能达到。

#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,k=0;
    cin>>n;
    int a[n+1]={0},b[n+1]= {0};
    for(int i=1; i<=n; i++)
    {
        cin>>a[i];
    }
    int l=1;
    for(int i=n;i>=1;)//倒序搜索
    {
        if(a[i]==i)
        {
            b[l]=a[i];
            l++;
            k++;
            for(int j=i;j<=n;j++)
            {
                a[j]=a[j+1];
            }
            i=n;//搜到了,数组上数的位置改变,从头开始搜
        }
        i--;
    }
    if(k==n)
    {
        for(int i=n;i>=1;i--)
        {
            printf("%d\n",b[i]);//倒序输出
        }
    }
    else printf("-1\n");
    //printf("%d\n",k);
    return 0;
}
### TSP (Traveling Salesman Problem) Code Implementation For the Traveling Salesman Problem, an efficient approach is using a greedy heuristic algorithm like the farthest insertion method for solving problems with more than ten points. For fewer points, brute force methods are applied due to their simplicity and effectiveness on small datasets[^1]. Below demonstrates how one might implement such algorithms. #### Farthest Insertion Heuristic Algorithm Example: This Python function implements the farthest insertion heuristic specifically designed for tackling larger instances of TSP efficiently while ensuring good performance without exhaustive search complexity. ```python import numpy as np from scipy.spatial import distance_matrix def nearest_node(unvisited, distances): min_dist = float('inf') closest_node = None for node in unvisited: dist = sum(distances[node]) if dist < min_dist: min_dist = dist closest_node = node return closest_node def tsp_far_insertion(points): n = len(points) # Calculate all pairwise Euclidean distances between cities. dists = distance_matrix(points, points) tour = [0] # Start at first city unvisited = set(range(1, n)) while unvisited: last = tour[-1] next_city = max((city for city in range(n) if city not in tour), key=lambda c: dists[last][c]) pos = min( ((i, dists[tour[i]][next_city] + dists[next_city][tour[(i+1)%n]] - dists[tour[i]][tour[(i+1)%n]]) for i in range(-len(tour), len(tour))), key=lambda x:x[1])[0] tour.insert(pos % len(tour)+1,next_city) unvisited.remove(next_city) cost = sum(dists[tour[i], tour[(i+1)%n]] for i in range(len(tour))) return tour, cost ``` The above code snippet defines two functions; `nearest_node` selects nodes based on minimum total distance criteria whereas `tsp_far_insertion` constructs tours iteratively adding furthest reachable vertices until completion. This strategy aims to minimize overall travel length effectively especially suitable for large scale scenarios beyond simple enumeration techniques feasible only within limited scope. #### Brute Force Method for Small Instances (<10 Points): When dealing with smaller sets containing less than or equal to nine elements, employing brute-force strategies becomes computationally viable offering optimal solutions albeit slower runtime compared against heuristics used previously mentioned. ```python from itertools import permutations def tsp_bruteforce(points): best_tour = None shortest_path_length = float('Inf') for perm in permutations(range(len(points))): path_length = sum(np.linalg.norm(points[perm[i]] - points[perm[i+1]]) for i in range(len(points)-1)) \ + np.linalg.norm(points[perm[-1]] - points[perm[0]]) if path_length < shortest_path_length: shortest_path_length = path_length best_tour = list(perm) return best_tour,shortest_path_length ``` In this version, every possible permutation gets evaluated calculating corresponding lengths before identifying minimal route covering each point exactly once returning both sequence alongside its associated metric value representing traveled span during traversal cycle.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值