QOJ.ac

QOJ

ID题目提交者结果用时内存语言文件大小提交时间测评时间
#197482#6503. DFS Order 3vanthoci#TL 1ms3468kbC++171.8kb2023-10-02 16:26:432023-10-02 16:26:43

Judging History

你现在查看的是最新测评结果

  • [2023-10-02 16:26:43]
  • 评测
  • 测评结果:TL
  • 用时:1ms
  • 内存:3468kb
  • [2023-10-02 16:26:43]
  • 提交

answer

#include<bits/stdc++.h>
#define fer(i,a,b) for(int i = a ; i <= b ; i ++)
const int N = 2e3 + 10 ;
using namespace std;

int f[N] ;
int a[N][N] ;

int find(int x)
{
    return f[x] == x ? f[x] : f[x] = find(f[x]) ;
}

vector<pair<int,int>> res ;
int id[N] ;


void de(vector<int> v)
{
    for(auto i : v)
        cout << i << " " ;
    cout << '\n' ;
}

void merge(int a , int b)
{
    int pa = find(a) , pb = find(b) ;
    if(pa != pb)
    {
        f[pa] = pb ;
        res.push_back({a , b}) ;
    }
}
void solution(){
    int n;
    cin>>n;
    res.clear() ;
    fer(i,1,n) f[i] = i , id[i] = 1 ;

    for(int i = 1 ; i <= n ; i ++)
    {
        fer(j,1,n)
            cin >> a[i][j] ;
        if(n >= 2)
            merge(a[i][1] , a[i][2]) ;
    }

    while(true)
    {
        set<int> q ;

        int ff = 0 ;
        fer(i,1,n)
        {
            int f = 0 ;
            while( id[i] <= n && find(a[i][id[i]]) == find(a[i][id[i] + 1]) )
                id[i] ++ ;
            
            //de(vector<int>{id[i] , id[i] + 1 , a[i][id[i]] , a[i][id[i] + 1] , find(a[i][id[i]]) , find(a[i][id[i] + 1]) }) ;
            if(id[i] + 1 <= n)
            {
                //cout << a[i][id[i] + 1] << '\n' ;
                q.insert(a[i][id[i] + 1]) , f = 1 ;
            }
            
            //cout << id[i] << '\n' ;

            if(f)
                ff = 1 ;
        }
        if(!ff)
            break ;

        merge(*q.begin(),*++q.begin()) ;
    }
    sort(res.begin(),res.end()) ;
    for(auto i : res)
        cout << i.first << " " << i.second << '\n' ;

    return ;
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    int T; cin >> T;
    while (T--) solution();
    return 0;
}


/*

1 2 
1 2
3 2
1 2
3 2
4 2
1 2
1 3
2 4
3 5
*/

詳細信息

Test #1:

score: 100
Accepted
time: 1ms
memory: 3468kb

input:

4
2
1 2
2 1
3
1 2 3
2 1 3
3 2 1
4
1 2 3 4
2 1 3 4
3 2 4 1
4 2 1 3
5
1 2 4 3 5
2 4 1 3 5
3 5 1 2 4
4 2 1 3 5
5 3 1 2 4

output:

1 2
1 2
3 2
1 2
3 2
4 2
1 2
1 3
2 4
3 5

result:

ok correct answer! (4 test cases)

Test #2:

score: -100
Time Limit Exceeded

input:

20000
10
1 2 4 5 6 7 3 8 10 9
2 1 4 5 6 7 3 8 10 9
3 8 1 2 4 5 6 7 10 9
4 5 6 7 1 2 3 8 10 9
5 4 6 7 1 2 3 8 10 9
6 7 4 5 1 2 3 8 10 9
7 6 4 5 1 2 3 8 10 9
8 3 1 2 4 5 6 7 10 9
9 10 1 2 4 5 6 7 3 8
10 1 2 4 5 6 7 3 8 9
10
1 4 3 8 2 9 6 5 7 10
2 8 9 6 3 4 1 5 7 10
3 8 2 9 6 4 1 5 7 10
4 1 3 8 2 9 6 5...

output:


result: