每次找打最小值放在前面。
#include<stdio.h>
#include<iostream>
#include<math.h>
#include<algorithm>
using namespace std;
int n,a[3100];
int main()
{
cin >> n;
for(int i = 0; i < n; i++)
cin >> a[i];
cout << n << endl;
for(int i = 0; i < n; i++)
{
int k = min_element(a + i, a + n) - a;//找到[a+i,a+n)里面的最小元素的下标
//cout << k << endl;
swap(a[i], a[k]);
cout << i << " " << k << endl;
}
return 0;
}
B - BerSU Ball:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define N 105
int a[N], b[N];
int hash1[N], hash2[N];
int main()
{
int n, m;
while(~scanf("%d", &n))
{
memset(hash1, 0, sizeof(hash1));
memset(hash2, 0, sizeof(hash2));
for( int i = 1; i <= n; i++ )
{
scanf("%d", &a[i]);
hash1[a[i]]++;
}
scanf("%d", &m);
for( int i = 1; i <= m; i++ )
{
scanf("%d", &b[i]);
hash2[b[i]]++;
}
int cnt = 0;
sort(a+1, a+1+n);
sort(b+1, b+1+m);
if ( n > m )
{
for( int i = 1; i <= n; i++ )
{
if( hash2[a[i]-1] )
{
hash2[a[i]-1]--;
cnt++;
continue;
}
if( hash2[a[i]] )
{
hash2[a[i]]--;
cnt++;
continue;
}
if( hash2[a[i]+1] )
{
hash2[a[i]+1]--;
cnt++;
continue;
}
}
}
else
{
for( int i = 1; i <= m; i++ )
{
if( hash1[b[i]-1] )
{
hash1[b[i]-1]--;
cnt++;
continue;
}
if( hash1[b[i]] )
{
hash1[b[i]]--;
cnt++;
continue;
}
if( hash1[b[i]+1] )
{
hash1[b[i]+1]--;
cnt++;
continue;
}
}
}
printf("%d\n", cnt);
}
return 0;
}
C - Given Length and Sum of Digits...
贪心。
#include <iostream>
using namespace std;
void lesss(int m, int s)
{
if (s == 0)
cout<<"0"<<endl;
else
{
if ((m-1)*9+1 >= s)
{
cout<<1;
s--;
m--;
}
while(m)
{
if ((m-1)*9 >= s)
{
cout<<0;
}
else
{
cout<<s-(9*(m-1));
s -= s-(9*(m-1));
}
m--;
}
}
}
void best(int m, int s){
while(m){
if (s > 9){
cout<<9;
s -= 9;
}
else{
cout<<s;
s = 0;
}
m--;
}
}
int main(){
int m, s;
cin>>m>>s;
if (s == 0 && m != 1)
{
cout<<"-1 -1"<<endl;
}
else
{
if (s > m*9)
{
cout<<"-1 -1"<<endl;
}
else
{
lesss(m, s);
cout<<" ";
best(m, s);
cout<<endl;
}
}
return 0;
}
D - Unbearable Controversy of Being
贪心:
每次边连出去的边到达的那个点计数一下,最后统计就行了
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
#define N 3005
using namespace std;
struct node{
int to, nxt;
}edge[N*10];
int head[N];
int cnt;
int n, m;
int ans;
int mat[N][N];
void init()
{
memset(head, -1, sizeof(head));
memset(mat, 0, sizeof(mat));
cnt = 1;
ans = 0;
}
void addedge( int u, int v )
{
edge[cnt].to = v;
edge[cnt].nxt = head[u];
head[u] = cnt++;
}
int f( int x )
{
return x * (x-1) / 2;
}
int main()
{
while(~scanf("%d%d", &n, &m))
{
init();
int a, b;
while(m--)
{
scanf("%d%d", &a, &b);
addedge(a, b);
}
for( int i = 1; i <= n; i++ )
{
for( int j = head[i]; ~j; j = edge[j].nxt )
{
int v = edge[j].to;
for( int k = head[v]; ~k; k = edge[k].nxt)
{
int o = edge[k].to;
mat[i][o]++;
}
}
}
for( int i = 1; i <= n; i++)
{
for( int j = 1; j <= n; j++ )
{
if(i == j)
continue;
ans += f(mat[i][j]);
}
}
printf("%d\n", ans);
}
return 0;
}