您的位置:首页 > 其它

POJ 1033

2016-02-25 13:57 323 查看
这是一道关于磁盘管理的题目。

题目大意:

磁盘中有N块簇,F块文件,每个文件分别分布在不同的簇中。默认,顺序查找速度最快。

问的是,怎么调整顺序使得各个文件按照簇的逻辑顺序排列。

举例:

假设原始顺序为:

 初始状态是这样的,0表示未占用:

  簇号:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

  逻辑编号:0 1 2 0 7 0 5 0 0 8 3 4 0 0 0 0 0 6



  一共整理到最后,磁盘的情况最后是这样的:

  簇号:  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

  逻辑编号:1 2 3 4 5 6 7 8 0 0 0 0 0 0 0 0 0 0

我们不妨假设cluster[i]表示第i块簇号对应的逻辑编号,分一下三种情况:

1.cluster[i] = i,默认不动

2.cluster[i] = 0,表示未占用,也不动

3.cluster[i]!=i,并且占用了

第三种情况可分为两种子情况(用栈来实现):

1.可构成环,例如

1 2 3 4 5 6

5 4 2 1 3 ……

2.可构成链

1 2 3 4 5 6

5 4 2 0 3 ……

下面看代码:

#include<iostream>
#include<stack>
using namespace std;

int cluster_num,file_num,file_size;
int cluster[10001];
int mov_num = 0;

stack<int>s;

int main(){
    cin>>cluster_num>>file_num;
    int i,j;
    int bp = 1;
    int temp;
    for(i=0;i<file_num;i++){
        cin>>file_size;
        for(j=0;j<file_size;j++){
            cin>>temp;
            cluster[temp] = bp;
            bp++;
        }
    }
    int next;
    for(i=1;i<=cluster_num;i++){
        if(cluster[i] == i)
            continue;
        else if(cluster[i] != 0){
            s.push(i);
            next = cluster[i];
            bool is_circle = false;   //判断它是否有环
            while(true){
                if(cluster[next] == i){
                    is_circle = true;
                    break;
                }
                if(cluster[next] == 0){
                    is_circle = false;
                    break;
                }
                s.push(next);
                next = cluster[next];
            }
            if(is_circle == true){
                for(j=cluster_num;j>0;j--){
                    if(cluster[j] == 0)
                        break;
                }
                cout<<next<<" "<<j<<endl;
                cluster[j] = cluster[next];
                while(!s.empty()){
                    temp = s.top();
                    cout<<temp<<" "<<next<<endl;
                    mov_num++;
                    cluster[next] = cluster[temp];
                    next = temp;
                    s.pop();
                }
                cluster[next] = cluster[j];
                cluster[j] = 0;
                cout<<j<<" "<<next<<endl;
                mov_num++;
            }
            else{
                while(!s.empty()){
                    temp = s.top();
                    cout<<temp<<" "<<next<<endl;
                    mov_num++;
                    cluster[next] = cluster[temp];
                    next = temp;
                    s.pop();
                }
                cluster[next] = 0;
            }
        }
    }
    if(mov_num == 0)
        cout<<"No optimization needed"<<endl;
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: