UVa 11330 (置换 循环的分解) Andy's Shoes

本文介绍了一种解决UVa11077问题的方法,通过固定左脚鞋子并视右脚鞋子为置换操作,分析了如何通过最少次数的交换使鞋子回到正确的位置。使用C++实现,并提供了完整的代码示例。

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

和UVa11077的分析很类似。

我们固定左脚的鞋子不动,然后将右脚的鞋子看做一个置换分解。

对于一个长度为l的循环节,要交换到正确位置至少要交换l-1次。

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <map>
 4 using namespace std;
 5 
 6 bool vis[10000 + 10];
 7 
 8 int main()
 9 {
10     //freopen("in.txt", "r", stdin);
11 
12     int T;
13     scanf("%d", &T);
14     while(T--)
15     {
16         int n, a, b;
17         map<int, int> m;
18         scanf("%d", &n);
19         for(int i = 0; i < n; i++)
20         {
21             scanf("%d%d", &a, &b);
22             m[a] = b;
23         }
24         int ans = 0;
25         map<int, int>::iterator It;
26         memset(vis, false, sizeof(vis));
27         for(It = m.begin(); It != m.end(); It++)
28         {
29             int i = It->first;
30             if(!vis[i])
31             {
32                 int cnt = 0;
33                 int j = i;
34                 do
35                 {
36                     cnt++;
37                     vis[j] = true;
38                     j = m[j];
39                 }while(j != i);
40                 ans += cnt - 1;
41             }
42         }
43         printf("%d\n", ans);
44     }
45 
46     return 0;
47 }
代码君

 

转载于:https://www.cnblogs.com/AOQNRMGYXLMV/p/4373121.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值