poj1033 Defragment

写了好几遍也wa了好几遍,其实不应该wa的,有个关键点没注意到:
环的时候,要将一个点移至 末尾 的一个空白位置,然后让后面的补上,最后再将该点从空白位置移回来
一开始直接把这个末尾定为n,实际上会有n被占用的情况

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>

using namespace std;

int n, k;
const int maxn = 10005;

int cluster[maxn];

int si, c;

bool need_optimalize = false;

stack<int> seq;

int main()
{
    memset(cluster, 0, sizeof(cluster));

    cin>>n>>k;

    int cnt = 0;
    for(int i=0; i<k; i++)
    {
        cin>>si;
        for(int j=0; j<si; j++)
        {
            cin>>c;
            cluster[c] = ++cnt;
        }
    }

    for(int i=1; i<=n; i++)
    {
        if(cluster[i]==i || !cluster[i])
            continue;

        need_optimalize = true;

        seq.push(i);
        int next = cluster[i];
        cluster[i] = i;

        bool isCircle = false;
        while (true) {
            if(cluster[next] == i){
                isCircle = true;
                break;
            }
            if(cluster[next] == 0)
                break;
            seq.push(next);
            next = cluster[next];
        }

        if (isCircle)
        {
            int j = n;
            while( cluster[j] )
                j--;

            printf("%d %d\n", next, j);
            while(!seq.empty())
            {
                int t = seq.top();
                seq.pop();
                printf("%d %d\n", t, next);
                cluster[next]=next;
                next = t;
            }
            printf("%d %d\n", j, next);
            cluster[next] = next;
        }
        else
        {
            cluster[next] = 0;
            while(!seq.empty())
            {
                int t = seq.top();
                seq.pop();
                printf("%d %d\n", t, next);
                cluster[next]=next;
                next = t;
            }
            cluster[next] = 0;
        }
    }

    if(!need_optimalize)
        puts("No optimization needed");

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值