給出一個n個數的序列1,然后有m個改動(a, b),在序列2中a跟b在序列中的相對順序改變。求符合題意的序列2。
題中說道如果一個數的位置不確定,則輸出‘?' ,仔細想想,這種情況是不會存在的,因為在給定的序列1中,所有數都會有相對順序,因此無論怎么修改數對的相對順序,結果總是確定的。
?
#include<algorithm> #include<iostream> #include<cstring> #include<cstdlib> #include<fstream> #include<sstream> #include<bitset> #include<vector> #include<string> #include<cstdio> #include<cmath> #include<stack> #include<queue> #include<stack> #include<map> #include<set> #define FF(i, a, b) for(int i=a; i<b; i++) #define FD(i, a, b) for(int i=a; i>=b; i--) #define REP(i, n) for(int i=0; i<n; i++) #define CLR(a, b) memset(a, b, sizeof(a)) #define debug puts("**debug**") #define LL long long #define PB push_back #define eps 1e-10 using namespace std; const int maxn = 555; int T, n, m, rank1[maxn], rank2[maxn], pos[maxn], in[maxn], g[maxn][maxn]; bool topo() { int tot = 0; queue<int> q; REP(i, n) if(in[i] == 0) q.push(i); while(!q.empty()) { int u = q.front(); q.pop(); rank2[tot++] = u; REP(v, n) if(g[u][v]) { in[v]--; if(in[v] == 0) q.push(v); } } return tot == n; } int main() { scanf("%d", &T); while(T--) { scanf("%d", &n); int a, b; REP(i, n) { scanf("%d", &rank1[i]);rank1[i]--; pos[rank1[i]] = i; } CLR(g, 0); CLR(in, 0); REP(i, n) FF(j, i+1, n) g[rank1[i]][rank1[j]] = 1, in[rank1[j]]++; scanf("%d", &m); while(m--) { scanf("%d%d", &a, &b);a--;b--; swap(g[a][b], g[b][a]); if(pos[a] < pos[b]) in[a]++, in[b]--; else in[a]--, in[b]++; } if(topo()) REP(i, n) printf("%d%c", rank2[i]+1, i == n-1 ? '\n' : ' '); else puts("IMPOSSIBLE"); } return 0; }
?
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
