Educational Codeforces Round 47 (Rated for Div. 2) D ---- Relatively Prime Graph

Educational Codeforces Round 47 (Rated for Div. 2) D ---- Relatively Prime Graph_第1张图片

暴力出奇迹,暴力枚举所有的组合如果满足了n个就ok,判断图是否可以联通,边数够不够m个,判断是否有答案。

因为提前知道了,n较大的时候,一定有满足个m的答案,因此实际时间复杂度应该不超过O(m)

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
int gcd(int n,int m) {return m == 0 ? n : gcd(m,n%m);}
struct node{ int u,v; } p[maxn];
int main(){
    int n,m,k = 0;
    cin >> n >> m;
    for (int i=1; i<=n && k < m; i++) {
        for (int j=i+1; j<=n && k < m; j++) {
            if (gcd(i, j) == 1) {
                p[k].u = i; p[k].v = j; k ++;
            }
        }
    }
    if (m < n-1 || k < m) {
        cout << "Impossible" << endl;
        return 0;
    }else{
        cout << "Possible" << endl;
    }
    for (int i=0; i<k; i++){
        cout << p[i].u << ' ' << p[i].v << endl;
    }
    return 0;
}

你可能感兴趣的:(Codeforce练习)