UVA 11330 Andy's Shoes(置换)

题意:给出n对不同颜色的鞋子,最开始鞋子的左右已经排好,但是颜色没有排好,问将所有鞋子的颜色也排好的最少交换次数是多少。

思路:其实就是给每个鞋子配对,我们将给出的n对鞋子按左边鞋子编号的顺序排好,那么就可以把这个看做是一个置换,那么对于每个右边的鞋子,要交换到相应的位置,每个长度为L的循环节要交换L-1次,求一下循环节就ok了。

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<algorithm>
#include<map>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#define inf 0x3f3f3f3f
#define Inf 0x3FFFFFFFFFFFFFFFLL
#define eps 1e-9
#define pi acos(-1.0)
using namespace std;
typedef long long ll;
const int maxn=10000+10;
int id[maxn];
bool vis[maxn];
int main()
{
    //freopen("in.txt","r",stdin);
    //freopen("out.txt","w",stdout);
    int t,n;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        int x,y;
        memset(id,0xff,sizeof(id));
        for(int i=1;i<=n;++i)
        {
            scanf("%d%d",&x,&y);
            id[x]=y;
        }
        memset(vis,0,sizeof(vis));
        int ans=0,cnt;
        for(int i=1;i<=10000;++i)
        {
            if(vis[i]||id[i]==-1) continue;
            int j=i;cnt=0;
            while(!vis[j])
            {
                vis[j]=true;
                cnt++;
                j=id[j];
            }
            ans+=(cnt-1);
        }
        printf("%d\n",ans);
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值