POJ1033

来源:互联网 发布:md5加密 java验证 编辑:程序博客网 时间:2024/05/01 00:11

题目链接:http://poj.org/problem?id=1033

 

package D0807;/*题目大意:给你有几个文件以及文件碎片现在的位置,要求给出操作方法, * 使得操作之后文件连续并且紧凑还有总体上文件时按照顺序摆放的。 * 例如样例:20 3 表示20个空间,3个文件4 2 3 11 12  * 第一个文件有4个碎片,分别在2,3,11,121 7 后面的一样 * 初始目标状态是:1~4是一号文件的碎片,5号是2号文件的碎片,6~8是3号文件的碎片...总之模拟碎片整理程序。 * 有2种不和谐因素:出现了环,或者链。 * 怎么说呢?环是指一些碎片,上一个碎片占据了下一个碎片应有的位置。然后最后一个占据了第一个位置。 * 而链就是最后一个的目标位置是空闲的 * */import java.util.*;import java.io.*;public class POJ1033 {static int clusters[] = new int[10001];   static int clusters_num, file_num;   static int counter = 1, move_num = 0;//文件片段的真实编号和操作的总数   static int next, i, j, t, n;   static Stack<Integer>s = new Stack<Integer>();static PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));public static void main(String[] args) throws IOException {StreamTokenizer st = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));st.nextToken();clusters_num = (int) st.nval;st.nextToken();file_num = (int) st.nval;for (i = 0; i < file_num; i++) {st.nextToken();n = (int)st.nval;for(j = 0;j<n;j++){st.nextToken();t = (int)st.nval;clusters[t] = counter++;}}doit();out.flush();}private static void doit() {// TODO Auto-generated method stubfor(i = 1;i<=clusters_num;i++){if(clusters[i]==i)continue;//如果刚好放在了目标位置上就不需要移动。else if(clusters[i]!=0){//位置上放了文件且位置错误s.push(i);next = clusters[i];boolean is_circle = false;while(true){//判断是否出现了环if(clusters[next]==i){is_circle = true;break;}else if(clusters[next]==0){is_circle = false;break;}s.push(next);next = clusters[next];}if(is_circle){for(j = clusters_num; j>=0; j--){if(clusters[j]==0)break;//从后向前找一个空位置,为解开环做准备}//System.out.println(next+" "+j);out.println(next+" "+j);clusters[j] = clusters[next];deal();clusters[next] = clusters[j];//把开始的结点移动回去  clusters[j] = 0;//System.out.println(j+" "+next);out.println(j+" "+next);}else{//没有环deal();clusters[next] = 0;}}}if(move_num==0)//System.out.println("No optimization needed");out.println("No optimization needed");}private static void deal() {// TODO Auto-generated method stubwhile(!s.isEmpty()){t  = s.peek();//System.out.println(t+" "+next);out.println(t+" "+next);clusters[next] = clusters[t];next = t;s.pop();move_num++;}}}


 

原创粉丝点击