Two Matchings 动态规划,思维

题目链接

题意解析:

题中matching指的就是一个逆元为本身的置换,并且要求不能有不变元。这样可知p中的数必定是两两配对的(互相映射),如果p的长度为奇数必定会剩余一个数与自己配对,则无法构成matching,故长度必为偶数
cost中由于i与pi是对称的(如1映射到5时,|a1-a5|与|a5-a1|计算了两次)。所以除2后,cost的含义为每次从a中取两个数,求其差的绝对值。

题解:

下面的提到的数组都是排好序后的
最小的取法:
其实我们需要找的就是一个使得cost最小的p和次小的q,显然最小就是排序后相邻的数两两相减(图1)。
图1

次小的取法:

  • 首先考虑n最小,n=4时
    如图2取法为仅有的一种:
    图2
  • 再看n=6时:
    图3
    这种取法是最小的,具体证明参考https://blog.csdn.net/m0_43448982/article/details/107431309
    上面两种取法都是与最小取法互补的,故result=2 *(尾-头)
  • 而n>6时,可以拆分为4与6的组合(由拓展欧几里得可推出4x+6y=n,n>=8且为偶数,x,y必有整数解),如果不拆分采用类似n=6的最优取法的话,必然没有拆分后的小(拆分后少了拆分的段与段的间隔的值)。所以能拆分就必拆分
    现在问题就变成了如何拆分数组了。总共就两种拆法,长度为4或6,但是明显无法贪心,所以可以想到采用动态规划。dp[i]定义为排序后前i个数取得的最小值,每次当前可选的状态为拆分成4或6

状态转移方程:

dp[i]=min(dp[i-4]+2*(arr[i]-arr[i-3]),dp[i-6]+2*(arr[i]-arr[i-5]));

不过需要注意先处理出来 i 等于4,6,8的情况(i=8时取不了6)

AC代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
const int MAX_N=2e5+5;
typedef long long ll;
ll dp[MAX_N];
ll arr[MAX_N];
inline int read()
{
	int sum=0,f=1;
	char c=getchar();
	while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
	while(c>='0'&&c<='9'){sum=(sum<<1)+(sum<<3)+c-'0';c=getchar();}
	return sum*f;
}
int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		int n;
		scanf("%d",&n);
		for(int i=1;i<=n;i++)arr[i]=read();
		sort(arr+1,arr+n+1);
		dp[4]=2*(arr[4]-arr[1]);
		dp[6]=2*(arr[6]-arr[1]);
		dp[8]=2*(arr[8]-arr[5]+arr[4]-arr[1]);
		for(int i=10;i<=n;i+=2)
		{
			dp[i]=min(dp[i-4]+2*(arr[i]-arr[i-3]),dp[i-6]+2*(arr[i]-arr[i-5]));
		}
		cout<<dp[n]<<'\n';
	}
	return 0;
}

还可参考:
https://www.cnblogs.com/whitelily/p/13338146.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 定向倒角匹配算法是用来在两个有向图之间寻找最大匹配的算法。 以下是用 Python 实现定向倒角匹配算法的示例代码: ``` from collections import defaultdict def find_matching(graph, matching, u, visited): """ Finds a matching for a given vertex using DFS. """ for v in graph[u]: if visited[v]: continue visited[v] = True if matching[v] == -1 or find_matching(graph, matching, matching[v], visited): matching[v] = u return True return False def max_matching(graph, n, m): """ Finds the maximum matching in a bipartite graph. """ # Initialize the matching to be empty. matching = [-1] * m # Keep track of the number of matchings found. matchings_count = 0 # Iterate through all vertices in the left part of the bipartite graph. for u in range(n): # Reset the visited array for each iteration. visited = [False] * m # Try to find a matching for the current vertex. if find_matching(graph, matching, u, visited): matchings_count += 1 return matchings_count, matching def visualize_matching(graph, matching, n, m): """ Visualizes the matching in a bipartite graph. """ # Initialize a dictionary to store the matchings for each vertex. matchings = defaultdict(list) # Iterate through all vertices in the right part of the bipartite graph. for v in range(m): # If the vertex is part of the matching, add it to the dictionary. if matching[v] != -1: matchings[matching[v]].append(v) # Print the matchings for each vertex. for u in range(n): print(f"Vertex {u} is matched with vertices {matchings[u]}") if __name__ == "__main__": # Example bipartite graph. graph = defaultdict(list) graph[0] = [1, 2] graph[1] = [2] graph[2] = [0, 3] graph[3] = [3] # Number of vertices in the left and right parts of the bipartite graph. n = 4 m = 4 # Find the maximum matching in the bipartite graph. matchings_count, matching = max_matching(graph, n, m) print(f"Found {matchings_count} matchings.") # Visualize the matching. visualize_matching(graph, matching, n, m) ``` 在上面的代码中 ### 回答2: 定向倒角匹配算法是一种用于图像处理中的特征匹配算法。在Python中,我们可以使用OpenCV库来实现该算法,并通过Matplotlib库来可视化每个点的匹配关系。 首先,我们需要导入所需的库: ```python import cv2 import numpy as np import matplotlib.pyplot as plt ``` 然后,我们可以定义一个函数来实现定向倒角匹配算法: ```python def directed_corner_matching(image1, image2): # 将图像转换为灰度图 gray1 = cv2.cvtColor(image1, cv2.COLOR_BGR2GRAY) gray2 = cv2.cvtColor(image2, cv2.COLOR_BGR2GRAY) # 创建SIFT特征提取器 sift = cv2.SIFT_create() # 检测关键点和计算其描述符 keypoints1, descriptors1 = sift.detectAndCompute(gray1, None) keypoints2, descriptors2 = sift.detectAndCompute(gray2, None) # 创建BFMatcher对象 bf = cv2.BFMatcher() # 使用knnMatch方法寻找最佳匹配 matches = bf.knnMatch(descriptors1, descriptors2, k=2) # 应用比例测试以获取最好的匹配 good_matches = [] for m,n in matches: if m.distance < 0.75*n.distance: good_matches.append(m) # 可视化匹配结果 result = cv2.drawMatches(image1, keypoints1, image2, keypoints2, good_matches, None, flags=2) plt.imshow(result) plt.axis('off') plt.show() ``` 最后,我们可以加载两个图像并调用该函数来执行匹配算法并可视化结果: ```python image1 = cv2.imread('image1.jpg') image2 = cv2.imread('image2.jpg') directed_corner_matching(image1, image2) ``` 这样,我们就实现了用Python实现定向倒角匹配算法,并可视化每个点的匹配关系。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值