【优化】HDU1856——The More The Better(顺便求解犇们JAVA版为啥不过)

来源:互联网 发布:java微信扫码支付开发 编辑:程序博客网 时间:2024/06/06 19:48

题目:点击打开链接

题目讲一个老师邀请尽量多的同学去家,这些同学应该都是朋友关系,问最多能有几个同学去。

这个题需要对序号进行优化,把树按顺序排起来,然后再进行比较,顺便不要忘了0的情况,有一个同学会去的。

这个题最初看的时间上 c++要求1000MS JAVA要求4000MS,也没推导出应该优化序号,用JAVA过了样例,但是提交上去是WA,时间也还充裕。。如果有大犇能帮忙改对了,小弟在此表示感谢了。。。最后附上WA代码。。

C++ AC代码:

#include <iostream>#include <string>#include <stdio.h>using namespace std;int father[10000009];int dep[10000009];int maxboy=1;int search_father(int tar){int result=tar;while(result!=father[result])result=father[result];return result;}void merge(int a,int b){int fx=search_father(a);int fy=search_father(b);if(fx!=fy){if(dep[fx]>dep[fy]){int temp=fy;fy=fx;fx=temp;}father[fx]=fy;dep[fy]=dep[fx]+dep[fy];if(maxboy<dep[fy]){maxboy=dep[fy];  //居然没有发现}}}int main(){int testcase=0;int a,b;while(cin>>testcase){maxboy=1;for(int i=0;i<10000009;i++)   //全部都要初始化{father[i]=i;dep[i]=1;   }for(int j=1;j<=testcase;j++){cin>>a>>b;merge(a,b);}printf("%d\n",maxboy);}return 0;}

JAVA WA代码:

import java.io.InputStreamReader;import java.util.Scanner;public class Main {static int father[]=new int [10000009];static int dep[]=new int [10000009];static int maxboy=1;static int search_father(int tar){int result=tar;while(result!=father[result])result=father[result];return result;}static void merge(int a,int b){int fx=search_father(a);int fy=search_father(b);if(fx!=fy){father[fx]=fy;dep[fy]=dep[fx]+dep[fy];if(maxboy<dep[fy]){maxboy=dep[fy];  //居然没有发现}}}public static void main(String args[]){int testcase=0;int a,b;Scanner cin=new Scanner(new InputStreamReader(System.in));while(cin.hasNextInt()){testcase=cin.nextInt();maxboy=1;for(int i=0;i<10000009;i++)   //全部都要初始化{father[i]=i;dep[i]=1;   }for(int j=1;j<=testcase;j++){a=cin.nextInt();b=cin.nextInt();merge(a,b);}System.out.println(maxboy);}}}