#include<bits/stdc++.h>usingnamespace std;typedeflonglong ll;constint N =1e6+10;int a[N], n;
ll cnt =0;int c[N];voidmerge_sort(int q[],int l,int r){if(l >= r)return;int mid =(l + r)>>1;merge_sort(q, l, mid),merge_sort(q, mid +1, r);int i = l, j = mid +1, k =0;while(i <= mid && j <= r){if(q[i]<= q[j]) c[k++]= q[i++];else{
cnt += mid - i +1;
c[k++]= q[j++];}}while(i <= mid) c[k++]= q[i++];while(j <= r) c[k++]= q[j++];for(int i = l, j =0; i <= r; i++, j++) q[i]= c[j];}intmain(){
cin >> n;for(int i =0; i < n; i++) cin >> a[i];merge_sort(a,0, n -1);
cout << cnt << endl;}
7-3 前t个组合结果
#include<bits/stdc++.h>usingnamespace std;typedeflonglong ll;constint N =50;int a[N];int n, r, t;voiddfs(int x,int num){if(!t || r - num > x)return;if(x ==0){for(int i = n; i >=1; i--)if(a[i]) cout <<" "<< i;
cout << endl;
t--;return;}if(num < r){
a[x]=1;dfs(x -1, num +1);}
a[x]=0;dfs(x -1, num);}intmain(){
cin >> n >> r >> t;dfs(n,0);}
7-4 跳马问题
#include<bits/stdc++.h>usingnamespace std;typedeflonglong ll;constint N =1010;int dx[]={2,1,-1,-2,-2,-1,1,2};int dy[]={1,2,2,1,-1,-2,-2,-1};int m, n, k, vis[N][N], a[N][N];int cnt;voidDFS(int x,int y,int num){
vis[x][y]= num;if(num == n * m){
cnt++;if(cnt == k){for(int i =1; i <= n; i++){for(int j =1; j <= m; j++){
cout << vis[i][j];if(j == m)
cout << endl;else
cout <<" ";}}exit(0);}for(int i =1; i <= n; i++)for(int j =1; j <= m; j++)
a[i][j]= vis[i][j];}for(int i =0; i <8; i++){int nx = x + dx[i], ny = y + dy[i];if(nx <=0|| nx > n || ny <=0|| ny > m || vis[nx][ny])continue;DFS(nx, ny, num +1);}
vis[x][y]=0;}intmain(){
ios::sync_with_stdio(false);
cin >> n >> m >> k;DFS(1,2,1);if(cnt == k)return0;if(!cnt)
cout <<"impossible";else{for(int i =1; i <= n; i++){for(int j =1; j <= m; j++){if(j !=1)
cout <<' ';
cout << a[i][j];}
cout << endl;}}}
7-5 加油站之最小加油次数
#include<bits/stdc++.h>usingnamespace std;typedeflonglong ll;constint N =1010;structgasStation{int len,p;}a[N];int n,L,P;intcmp(gasStation x,gasStation y){return x.len < y.len;}intmain(){
ios::sync_with_stdio(false);
cin>>n;for(int i=0;i<n;i++) cin>>a[i].len>>a[i].p;
cin>>L>>P;for(int i=0;i<n;i++) a[i].len = L - a[i].len;sort(a,a+n,cmp);int ans =0,now =0;
queue<int>q;for(int i=0;i<n;i++){while(P < a[i].len - now){if(!q.size()){
cout<<-1<<endl;return0;}else{
P += q.front();
q.pop();
ans ++;}}
P -= a[i].len - now;
now = a[i].len;
q.push(a[i].p);}
cout<<ans<<endl;}
7-6 删数问题
#include<bits/stdc++.h>usingnamespace std;typedeflonglong ll;constint N =300;int n, k;int a[N];
string s;intmain(){
cin >> s >> k;
n = s.length();for(int i =0; i < n; i++) a[i]= s[i]-'0';while(k--){int f =0;for(int i =0; i < n; i++){if(a[i]> a[i +1]){
f =1;for(int j = i; j < n; j++)
a[j]= a[j +1];}if(f)break;}
n--;}int flag =1;for(int i =0; i < n; i++){if(s[i]=='0'&& i < n -1&& flag)continue;else{
cout << a[i];
flag =0;}}}