This problem has huge input data,use scanf() instead of cin to read data to avoid time limit exceed.
OUTPUT DETAILS:
FR builds the three lifts. Using (1, 1) as the lower-left corner,
the lifts are (3, 1) <-> (8, 2), (7, 3) <-> (5, 2), and (1, 3) <->
(2, 2). All locations are now connected. For example, a cow wishing
to travel from (9, 1) to (2, 2) would ski (9, 1) -> (8, 1) -> (7,
1) -> (7, 2) -> (7, 3), take the lift from (7, 3) -> (5, 2), ski
(5, 2) -> (4, 2) -> (3, 2) -> (3, 3) -> (2, 3) -> (1, 3), and then
take the lift from (1, 3) - > (2, 2). There is no solution using
fewer than three lifts.
- #include<stdio.h>
- #include<string.h>
- #include<stack>
- #define INF 1000010
- #define P 261010
- using namespace std;
- stack<int>S;
- int a[550][550],map[P][10],low[P],dfn[P];
- int instack[P];
- int bnt,be[P],n,m;
- int index,in[P],out[P];
- void build(){
- for(int i=1;i<=n;i++)
- for(int j=1;j<=m;j++){
- if(a[i][j]>=a[i-1][j])map[j+m*i-m][++map[j+m*i-m][0]] = j+(i-2)*m;
- if(a[i][j]>=a[i+1][j])map[j+m*i-m][++map[j+m*i-m][0]] = j+i*m;
- if(a[i][j]>=a[i][j+1])map[j+m*i-m][++map[j+m*i-m][0]] = j+(i-1)*m+1;
- if(a[i][j]>=a[i][j-1])map[j+m*i-m][++map[j+m*i-m][0]] = j+(i-1)*m-1;
- }
- }
- void tarjan(int i){
- dfn[i] = low[i] = ++index;
- S.push(i);
- instack[i] = 1;
- for(int j = 1;j<=map[i][0];j++){
- int k = map[i][j];
- if(!dfn[k]){
- tarjan(k);
- low[i] = min(low[i],low[k]);
- }
- else if(instack[k]){
- low[i] = min(low[i],dfn[k]);
- }
- }
- if(dfn[i]==low[i]){
- bnt++;
- int kk;
- do{
- kk = S.top();
- S.pop();
- instack[kk] = 0;
- be[kk] = bnt;
- }while(i!=kk);
- }
- }
- int main(){
- while(~scanf("%d%d",&m,&n)){
- int ans,ans1;
- memset(dfn,0,sizeof(dfn));
- memset(in,0,sizeof(in));
- memset(out,0,sizeof(out));
- memset(instack,0,sizeof(instack));
- bnt = ans = ans1 = index = 0;
- for(int i=0;i<=n+1;i++)a[i][0] = a[i][m+1] = INF;
- for(int j=0;j<=m+1;j++)a[0][j] = a[n+1][j] = INF;
- for(int i=1;i<=n;i++){
- for(int j=1;j<=m;j++){
- scanf("%d",&a[i][j]);
- map[j+(i-1)*m][0] = 0;
- }
- }
- build();
- for(int i=1;i<=n*m;i++)
- if(!dfn[i])
- tarjan(i);
- for(int i=1;i<=n*m;i++){
- for(int j =1;j<=map[i][0];j++)
- if(be[i]!=be[map[i][j]]){
- out[be[i]]++;
- in[be[map[i][j]]]++;
- }
- }
- for(int i=1;i<=bnt;i++){
- if(out[i]==0)ans++;
- if(in[i]==0)ans1++;
- }
- if(bnt==1)printf("0\n");
- else printf("%d\n",max(ans,ans1));
-
- }
- }
- 在POJ能过,在杭电就过不了,是什么原因啊,。。。。。。??!坑爹啊